How can I round the number to the nearest value of lower modulus in C #. For example, in Excel there is a formula for this: = ROUND (number; number of digits).
For example, round the number 1 545 978, 80 -> 1 545 000.00
How can I round the number to the nearest value of lower modulus in C #. For example, in Excel there is a formula for this: = ROUND (number; number of digits).
For example, round the number 1 545 978, 80 -> 1 545 000.00
There is no built-in function to perform this action. But you can always write your own, for example:
double roundDown(double number, int p) { return Math.Round(number - number % Math.Pow(10, p)); } Call example
roundDown(1545978.80, 3) // 1545000.0 Let the initial number 1545978.80 and need to get 1545000.00
To get from the original number, subtract 978.80 .
This is the remainder of dividing the original number by 1000, which in turn is 10 3 , where 3 is the number of zeros before the comma.
Decimals make sense only for decimal numbers, for double concept of decimal places is meaningless .
For ordinary rounding ( Round ) there is a function out of the box: Decimal.Round(Decimal, Int32) . Decimal.Round(Decimal, Int32) .
But for rounding down you have to write yourself:
static decimal Truncate(decimal d, int places) => Shift(Math.Truncate(Shift(d, places)), -places); static decimal Shift(decimal d, int places) { if (places >= 0) { for (int i = 0; i < places; i++) d /= 10m; } else { for (int i = 0; i < -places; i++) d *= 10m; } return d; } public double Floor(double num, int rank) { if (rank == 0) return Math.Truncate(num); num /= Math.Pow(10, -rank); num = Math.Truncate(num); num *= Math.Pow(10, -rank); return num; } Math.Truncate ? - VladDTry playing with Math.Floor (...), Math.Ceiling (...), Math.Round (...)
public string down(double number, int digit) { var a = number; a /= Math.Pow(10, digit); a = Math.Round(a, 0); a *= Math.Pow(10, digit);; return $"{a},00"; } Something like that. Crooked, but your task performs. I think it's worth digging this way.
Source: https://ru.stackoverflow.com/questions/694133/
All Articles
double, never-never. For financial calculations onlydecimal. - VladD