Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not rounding properly

Tags:

c#

rounding

Math.Round(keyRate, 5).ToString("N5")

If keyRate is a number like 3.7066666666, you will see 3.70666 rather than 3.70667

What could be the issue here?

like image 452
slandau Avatar asked Nov 29 '25 15:11

slandau


1 Answers

The Math.Round function used what's called banker's rounding by default. Banker's rounding rounds toward the even number. To get the more traditional type of rounding, call the Round method like this:

Math.Round(3.7066666666, 5, MidpointRounding.AwayFromZero);

correction: After looking again at @slandau's number I realized that banker's rounding isn't the issue here. Banker's rounding only applies when the fractional portion of the number to the right of the desired precision is exactly halfway between two values. In other words

Math.Round(3.7066650000, 5, MidpointRounding.AwayFromZero) = 3.70667

while the following (Banker's rounding)

Math.Round(3.7066650000, 5, MidpointRounding.ToEven) = 3.70666

@slandau's result should be 3.70667 either way.

like image 55
WarrenG Avatar answered Dec 01 '25 07:12

WarrenG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!