四舍五入没有分数的小数不会添加分数

Rounding a decimal without fractions doesn't add fractions

我有以下代码:

var voucherAmountValue = "5";
var totalValue = Math.Round(Convert.ToDecimal(voucherAmountValue), 2);

当我将 totalValue 写入控制台时,它会打印 5。我希望添加小数位,为 totalValue 打印 5.00,但它没有:它仍然打印 5.

如何将小数位添加到没有小数位的小数位?

据我了解,您有一个整数值。所以要四舍五入并有余数,试试这个代码:

int k = 5;
var totalValue = Math.Round(Convert.ToDecimal(k)).ToString(".00");

第二行代码表示:

  1. 整数值k转换为浮点数

  2. Round() 静态方法 class Math 将值舍入到最接近的整数或指定的小数位数。

  3. ToString(".00") 表示转成字符串类型。 .ToString(".00") 意味着你总是会看到是否有空值。如果您不想看到空值,请使用此 .ToString(".##");

使用

var totalValue = ((decimal)voucherAmountValue/100)*100;

这里的问题是 Math.Round 添加 小数位,它只 限制 它们。

测试一下:

decimal a = 5m;
decimal b = Math.Round(a, 2); // b will be 5
a = 5.00m;
b = Math.Round(a, 3); // b will be 5,00 (not 5,000)
b = Math.Round(a, 2); // b will be 5,00
b = Math.Round(a, 1); // b will be 5,0

如你所见,如果原始字符串只包含"5",那么十进制值也将是5,而调用Math.Round(..., 2);只会是限制小数位数向下到2,如果小于2则不会补缺小数零。

您可以解决这个问题,方法是显式评估将强制创建这些数字的表达式:

var totalValue = Math.Round((Convert.ToDecimal(voucherAmountValue) / 100.0m) * 100.0m, 2);