Rounding to at least 2 to 4 decimal places
How can I round a decimal
to at least 2 decimal places and have it kept as a decimal
?
I know I can do this, but it has a开发者_开发百科 code smell.
var myResult = Decimal.Parse(myDecimal.ToString("0.00##"));
These are the expected results.
0.028 -> 0.028
0.02999 -> 0.03
You can use
Math.Round(myResult, 4);
a decimal
doesnt (or, perhaps shouldn't) have a "number of decimal places" until you format it for display.
decimal.Round(Decimal myDecimal, int digits#);
EX:
decimal.Round(100.555555, 2); // result = 100.56
Or
Math.Round(Decimal myDecimal, int digits#);
EX:
Math.Round(100.555555, 2); // result = 100.56
Check out the Math.Round(decimal, Int32) method:
Math.Round(myDecimal, 4);
try to use f format specifier
var myResult = Decimal.Parse(myDecimal.ToString("f"));
精彩评论