简体   繁体   中英

Why in c# 2.135 is always rounded (using 2 decimals) to 2.13

When using Math.Round(doubleValue, 2) // ToEven by default

// 2.135 --> 2.13 why not 2.14?

// 3.135 --> 3.14

And when using AwayFromZero 2.135 rounds at 2.13 why not 2.14?

To answer the question from your title:

2.135 is not always rounded(using 2 decimals) to 2.13, this just happens in your case because you are using a binary floating point data type. (As leppie pointed out, 2.135 cannot be represented accurately as a double, please note also that Microsoft seems to disinguish between decimal and floating point types , even though decimal also fits the definition)

If you were however to use decimal as data type instead you will have consistent behaviour in rounding, you can compare the different outputs from this snippet to verify:

decimal val1 = 2.135m;
decimal val2 = 3.135m;

Console.WriteLine("decimal val1({0}) rounded = {1}", val1, Math.Round(val1, 2));
Console.WriteLine("decimal val2({0}) rounded = {1}", val2, Math.Round(val2, 2));

double dval1 = 2.135;
double dval2 = 3.135;

Console.WriteLine("double val1({0}) rounded = {1}", dval1, Math.Round(dval1, 2));
Console.WriteLine("double val2({0}) rounded = {1}", dval2, Math.Round(dval2, 2));

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