简体   繁体   中英

Not rounding properly

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?

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.

You should use decimal and Math.Round(keyRate, 5, MidpointRounding.AwayFromZero)
It isn't work with double

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM