开发者

Rounding to at least 2 to 4 decimal places

开发者 https://www.devze.com 2023-03-24 06:45 出处:网络
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.

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"));
0

精彩评论

暂无评论...
验证码 换一张
取 消