如何设置.Net十进制值中的小数位数

时间:2019-12-03 03:14:14

标签: c# .net

.Net中的十进制值存储精度,这意味着有效存储尾随零,并在转换为字符串时显示它们。

1.00M.ToString();  // Returns "1.00"
1.M.ToString();    // Returns "1"

有没有一种简单的方法可以将精度设置为十进制值?

使用Round()不会这样做。它将降低精度,但不会提高精度。

decimal.Round(1.234M, 2).ToString(); // Returns "1.23"
decimal.Round(1M, 2).ToString();     // Still returns "1"

请注意,有几种方法可以格式化小数位数以显示给定数量的小数位数,但这不是我的问题。我想更改十进制值以具有特定的精度。我本希望在System.Decimal中有针对此功能,但我看不到它。

我有几种可行的方法,但是它们是很棒的黑客。

decimal d = 1M;
// 'Bruise' the number to give it more decimal places and then take some away.
// Obviously could cause errors, but may be safe if you know the numbers involved (still ugly).
decimal.Round(d + 0.00001M, 2).ToString(); // Returns "1.00"

// Format to a string at the desired precision and then parse.
decimal d2;
decimal.TryParse(d.ToString("#.00"), out d2);
d2.ToString(); // Returns "1.00"

看起来可以使用Decimal.GetBits()来完成,但我希望有一种更简单的方法。

0 个答案:

没有答案