NET System.Math.Round(2429402.5) function fails and rounds down with 2429402.0
772
Could someone please explain to me why the .NET Math.Round function fails when executing System.Math.Round(2429402.5), it does not round up, the result is 2429402.0and not 2429403.0.
I can't figure out if it's a framework error or the number.
The behavior is according to the documentation of the function Math.Round(Decimal) . For the behavior that you require, the most recommended is to use Math.Round(Decimal, Int32, MidpointRounding) since you can indicate the number of decimals and how the rounding will behave
Return Value Type: System.Double The closest integer to . If the fractional component of a is halfway between two integers, one of which is even and one of which is odd, then the even number is returned. Note that this method returns a double instead of an integer type.
Your result is between 2429402and 2429403, the documentation says that if it is between an odd or even number, return even.
It is that it Math.Roundseeks the closest not the largest, for that you must use Math.Ceiling
Math.Ceilinwill return the largest integer following the number you pass to it as a parameter, there is also another function Math.Floorthat does the exact opposite of Ceiling.
The behavior is according to the documentation of the function Math.Round(Decimal) . For the behavior that you require, the most recommended is to use Math.Round(Decimal, Int32, MidpointRounding) since you can indicate the number of decimals and how the rounding will behave
Result
This happens as the documentation says
Your result is between
2429402
and2429403
, the documentation says that if it is between an odd or even number, return even.Documentation
The function that best suits my need was the following:
this function allows me to round the number up and down without any problem with the data types, thanks to all.
It is that it
Math.Round
seeks the closest not the largest, for that you must useMath.Ceiling
Math.Ceilin
will return the largest integer following the number you pass to it as a parameter, there is also another functionMath.Floor
that does the exact opposite ofCeiling
.examples:
Program output:
References: