System.Globalization.NumberFormatInfo 停止舍入数字

System.Globalization.NumberFormatInfo Stop Rounding Number

我正在使用 System.Globalization.NumberFormatInfo class 使用以下代码格式化我的号码。

int decimalDigits = 4;
NumberFormatInfo format = new NumberFormatInfo();
format.CurrencyDecimalDigits = decimalDigits;
format.CurrencyDecimalSeparator = ".";
format.CurrencyGroupSeparator = ",";
format.CurrencySymbol = "";

string value = amount.ToString("C", format);

上面的代码格式化数字很好,但我有一个四舍五入的问题。

假设我输入了金额12345.12345,现在我想要的值是12,345.1234 但它 returns 12,345.1235.

所以基本上我想停止四舍五入,我在互联网上搜索但找不到我要找的东西。

String.Format 会在格式化时舍入浮点值,因此您需要在格式化值之前应用您自己的 "rounding rule"。我的理解是你想截断这个值。

当使用 Math.Round 对值进行舍入时,您可以指定精度。但是,当使用 Math.Truncate 截断时,您没有这样的选择。相反,您必须乘以和除以 10 的精度次方(在您的情况下为 10,000):

var factor = Math.Pow(10, decimalDigits);
var truncatedAmount = Math.Truncate(factor*amount)/factor;
string value = truncatedAmount.ToString("C", format);

这将产生所需的输出 12.345.1234

您的解决方案在这里:

amount = Math.Floor(amount * Math.Pow(10, decimalDigits)) / Math.Pow(10, decimalDigits);

使用前

string value = amount.ToString("C", format);