简体   繁体   中英

Rounding double to 4 digit precision has unexpected behavior

I am rounding a particular double value and expecting a certain result but it isn't coming through. This makes me curious if there is a flaw or am I missing something in the underlying logic.

See the following code snippet:

double value = 0.01075;
Console.WriteLine(Math.Round(value, 4, MidpointRounding.AwayFromZero));

Produces

0.0107

Using the AwayFromZero makes me think it should do 0.0108. I have tried several different examples (as seen below) and get the expected result in every instance except the one I listed above. HELP??!

double value = 0.010075;
Console.WriteLine(Math.Round(value, 5, MidpointRounding.AwayFromZero));
// 0.01008

value = 0.01075;
Console.WriteLine(Math.Round(value, 4, MidpointRounding.AwayFromZero));
// 0.0107

value = 0.010750000001;
Console.WriteLine(Math.Round(value, 4, MidpointRounding.AwayFromZero));
// 0.0108

value = 0.01065;
Console.WriteLine(Math.Round(value, 4, MidpointRounding.AwayFromZero));
// 0.0107

value = 0.01055;
Console.WriteLine(Math.Round(value, 4, MidpointRounding.AwayFromZero));
// 0.0106

value = 0.0175;
Console.WriteLine(Math.Round(value, 3, MidpointRounding.AwayFromZero));
// 0.018

value = 0.175;
Console.WriteLine(Math.Round(value, 2, MidpointRounding.AwayFromZero));
// 0.18

value = 0.75;
Console.WriteLine(Math.Round(value, 1, MidpointRounding.AwayFromZero));
// 0.8

NOTE: Using Visual Studio Pro 2015 with .Net 4.5.2

Most decimal numbers can't be represented exactly as floating point numbers. The closest double value to 0.01075 happens to be 0.0107499999999999991395771559155 , at least according to this calculator . That's not the midpoint between 0.0107 and 0.0108 , so the midpoint rounding mode doesn't come into play.

Incidentally, this is why you never use floating points for money.

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