Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

rounding

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?

like image 845
telebog Avatar asked Dec 04 '14 10:12

telebog


People also ask

Why learn C?

Why Learn C? There are an awful lot of programming languages available right now -- everything from the extremely high level (such as Visual Basic) to the low level power of assembly, and a good variety of specialized options in between ( Perl, Ruby, and Python are good choices for many tasks).

Why do so many programmers use C?

Plus, with C, you get lots of strong opinions mixed with insights that you can understand. As a result of its age and its use as the language of system programming for Unix, C has become something of the lingua franca of programming. C is a great language for expressing common ideas in programming in a way that most people are comfortable with.

What does %C mean in C programming?

While it's an integer, the %c interprets its numeric value as a character value for display. For instance for the character a: If you used %d you'd get an integer, e.g., 97, the internal representation of the character a using %c to display the character ' a ' itself (if using ASCII)

Why do we use %C instead of %s in D?

Also, when using %c you want a character printed, not a number. In the D language, you would always use %s and let the compiler worry about the types. @MatejNanut No, integer types smaller than int are promoted to int when being passed into a variadic function. @Pubby: thank you, I didn't know that.


1 Answers

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));
like image 180
DrCopyPaste Avatar answered Nov 14 '22 22:11

DrCopyPaste