For example.
Math.Round(2.314, 2) //2.31
Math.Round(2.301, 2) //2.3 , but I want this as 2.30
For example.
Math.Round(2.314, 2) //2.31
Math.Round(2.301, 2) //2.3 , but I want this as 2.30
Numbers don't have any conception of zeroes after a decimal point.
You're actually asking how to convert the number into a string with extra zeroes:
(2.301).ToString("0.00") // "2.30"
See numeric format strings for more detail.
In particular, the 0
specifier will round away from zero.
You want a string formatting of the number:
string val = Math.Round(2.301, 2).ToString("F2");
2.3 and 2.30 are the same thing. If you want the string 2.30 then use .ToString("F2") on the Math.Round function.
2.3 and 2.30 is the same thing from a code perspective. You can display the trailing zero by formatting a string:
string yourString = Math.Round(2.301, 3).ToString("0.00");
The decimal is still there, you're probably just not seeing because when you look at the string representation, by default it will omit trailing zeros. You can overwrite this behavior by passing a format string to ToString()
:
Console.WriteLine(Math.Round(2.301, 2).ToString("N2")) // 2.30
But of course, if this is just for display purposes, you don't really need to call Math.Round
:
Console.WriteLine(2.301.ToString("N2")) // 2.30
Further Reading
If you use decimal
numbers (their literals end with m
, for "money"), you get the behavior you're after. double
numbers don't have a concept of significant zeroes the same way that decimal
s do.
Math.Round(2.314m, 2);
Math.Round(2.301m, 2);
Or if you want to change how you see the numbers, you can use a string format:
Math.Round(2.314, 2).ToString("N2");
Math.Round(2.301, 2).ToString("N2");