Math.Round does not store trailing zero

I need all values ​​to be rounded to two decimal places. So 1.401 should round to 1.40, but Math.Round(value, 2) rounds to 1.4.

How can I force a trailing zero?

+7
source share
7 answers

1.4 same as 1.40 - you just want to display it in different ways. Use a format string when calling ToString - for example, value.ToString("0.00")

+17
source

1.4 == 1.40 only time you need the final 0, you will see the number..ie format it to the line.

 .ToString("N2"); 
+12
source

Trailing zero is formatting rather than value, so use

 foo.ToString("0.00") 
+5
source

Trailing zero is just a presentation. Mathematically, 1.40 and 1.4 equivalent.

Instead, use formatting to represent it with two decimal places:

 String.Format("{0:0.00}", 1.4); or yourNumber.ToString("0.00"); 
+2
source

I know this is an old question, but it can help someone!

I use the C # xml class to populate and then serialize to xml. One of the values ​​is double. If I assign the value "7", it will be serialized to "7" when I really need "7.00". The easiest way to get around this was simple:

 foo = doubleValue + 0.00M 

And that makes the value 7.00 instead of 7. Thought it was better than doing a ToString and then taking it apart.

+2
source

This is a number (double?), So it does not have a trailing zero - you must make its text and force a trailing zero.

+1
source

This is due to the use of decimal or double number.

While inside (as shown in the Source Code ) Math.Round() saves trailing zeros even in double, nevertheless, the fact that it is stored as double zeros in memory forces all trailing zeros to be automatically deleted.

So, if you need trailing zeros, you can use the string display functions to format them as others have answered, or remember to pass the original value as a decimal number (causing use inside Decimal.Math.Round , which will only handle decimal places ), and do not leave the result double, and also do not save it in a double variable.

Similarly, if you have a decimal number and you do not need trailing zeros, just add it to double (you can either enter the input in Math.Round or the result, it does not matter if somewhere in the path becomes double).

0
source

All Articles