如何将小数值四舍五入到小数点后两位(用于在页面上输出)
题
当显示当前的小数值时 .ToString()
, ,它精确到小数点后 15 位,并且由于我用它来表示美元和美分,所以我只希望输出为小数点后 2 位。
我使用的变体是 .ToString()
为了这?
解决方案
decimalVar.ToString ("#.##"); // returns "" when decimalVar == 0
或
decimalVar.ToString ("0.##"); // returns "0" when decimalVar == 0
其他提示
我知道这是一个老问题,但我很惊讶地看到似乎没有人发布答案;
- 没有使用银行家四舍五入
- 未将值保留为小数。 醇>
这就是我要用的:
decimal.Round(yourValue, 2, MidpointRounding.AwayFromZero);
decimalVar.ToString("F");
这会:
- 四舍五入到小数点后两位,例如。23.456 => 23.46
- 确保有 始终是小数点后 2 位,例如。23 => 23.00, 12.5 => 12.50
非常适合货币和显示货币金额。
有关 ToString("F") 的文档: http://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx#FFormatString (感谢乔恩·施奈德)
如果您只需要这个用于显示,请使用string.Format
String.Format("{0:0.00}", 123.4567m); // "123.46"
http://www.csharp-examples.net/string-format-double /
“m”。是十进制后缀。关于十进制后缀:
给定十进制d = 12.345; 表达式 d.ToString(" C")或 String.Format(" {0:C}" ;,d)收益 $ 12.35 - 请注意使用当前文化的货币设置,包括符号。
请注意“C” 使用当前文化中的位数。您始终可以使用 C {Precision specifier}
覆盖default以强制必要的精度,如 String.Format(" {0:C2}",5.123d)
。
如果您希望用逗号和小数点(但没有货币符号)格式化,例如3,456,789.12 ......
decimalVar.ToString("n2");
已经有两个高得分的答案引用了Decimal.Round(...),但我认为还需要更多的解释 - 因为Decimal的一个意想不到的重要属性并不明显。
十进制'知道'根据它来自何处的小数位数。
例如,以下内容可能出乎意料:
Decimal.Parse("25").ToString() => "25"
Decimal.Parse("25.").ToString() => "25"
Decimal.Parse("25.0").ToString() => "25.0"
Decimal.Parse("25.0000").ToString() => "25.0000"
25m.ToString() => "25"
25.000m.ToString() => "25.000"
使用 Double
执行相同的操作将不会为上述每一个提供小数位(" 25"
)。
如果你想要一个十进制到2位小数,那么大概有95%的可能性,因为它是货币,在这种情况下95%的情况下这可能很好:
Decimal.Parse("25.0").ToString("c") => "$25.00"
或者在XAML中你只需使用 {Binding Price,StringFormat = c}
我遇到一个需要十进制AS小数的情况是将数据发送到亚马逊的网络服务时。该服务抱怨,因为十进制值(最初来自SQL Server)被发送为 25.1200
并被拒绝,( 25.12
是预期的格式)。
我需要做的只是 Decimal.Round(...)
,带有2个小数位来解决问题。
// This is an XML message - with generated code by XSD.exe
StandardPrice = new OverrideCurrencyAmount()
{
TypedValue = Decimal.Round(product.StandardPrice, 2),
currency = "USD"
}
TypedValue
的类型为 Decimal
,因此我不能只执行 ToString(" N2")
并需要对其进行舍入并保持它作为 decimal
。
这是一个显示不同格式的Linqpad程序:
void Main()
{
FormatDecimal(2345.94742M);
FormatDecimal(43M);
FormatDecimal(0M);
FormatDecimal(0.007M);
}
public void FormatDecimal(decimal val)
{
Console.WriteLine("ToString: {0}", val);
Console.WriteLine("c: {0:c}", val);
Console.WriteLine("0.00: {0:0.00}", val);
Console.WriteLine("0.##: {0:0.##}", val);
Console.WriteLine("===================");
}
结果如下:
ToString: 2345.94742
c: $2,345.95
0.00: 2345.95
0.##: 2345.95
===================
ToString: 43
c: $43.00
0.00: 43.00
0.##: 43
===================
ToString: 0
c: <*>.00
0.00: 0.00
0.##: 0
===================
ToString: 0.007
c: <*>.01
0.00: 0.01
0.##: 0.01
===================
这些都不是我所需要的,强制 2 d.p。并向上舍入为 0.005 - &gt; 0.01 代码>
强迫2 d.p.需要将精度提高2 d.p.确保我们至少有2 d.p.
然后四舍五入以确保我们没有超过2 d.p。
Math.Round(exactResult * 1.00m, 2, MidpointRounding.AwayFromZero)
6.665m.ToString() -> "6.67"
6.6m.ToString() -> "6.60"
如果值为0,您很少需要空字符串。
decimal test = 5.00;
test.ToString("0.00"); //"5.00"
decimal? test2 = 5.05;
test2.ToString("0.00"); //"5.05"
decimal? test3 = 0;
test3.ToString("0.00"); //"0.00"
评分最高的答案不正确,浪费了10分钟(大多数)人的时间。
评分最高的答案描述了一种格式化十进制值的字符串表示的方法,它可以正常工作。
但是,如果您确实想要将保存的精度更改为实际值,则需要编写如下内容:
public static class PrecisionHelper
{
public static decimal TwoDecimalPlaces(this decimal value)
{
// These first lines eliminate all digits past two places.
var timesHundred = (int) (value * 100);
var removeZeroes = timesHundred / 100m;
// In this implementation, I don't want to alter the underlying
// value. As such, if it needs greater precision to stay unaltered,
// I return it.
if (removeZeroes != value)
return value;
// Addition and subtraction can reliably change precision.
// For two decimal values A and B, (A + B) will have at least as
// many digits past the decimal point as A or B.
return removeZeroes + 0.01m - 0.01m;
}
}
示例单元测试:
[Test]
public void PrecisionExampleUnitTest()
{
decimal a = 500m;
decimal b = 99.99m;
decimal c = 123.4m;
decimal d = 10101.1000000m;
decimal e = 908.7650m
Assert.That(a.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
Is.EqualTo("500.00"));
Assert.That(b.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
Is.EqualTo("99.99"));
Assert.That(c.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
Is.EqualTo("123.40"));
Assert.That(d.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
Is.EqualTo("10101.10"));
// In this particular implementation, values that can't be expressed in
// two decimal places are unaltered, so this remains as-is.
Assert.That(e.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
Is.EqualTo("908.7650"));
}
您可以使用system.globalization格式化任何所需格式的数字。
例如:
system.globalization.cultureinfo ci = new system.globalization.cultureinfo("en-ca");
如果您有 decimal d = 1.2300000
,并且您需要将其修剪为2位小数,那么它可以像 d.Tostring(&quot; F2&quot;,ci)那样打印;
其中F2是字符串格式化为2位小数,ci是locale或cultureinfo。
了解更多信息,请查看此链接
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
Mike M.的回答对我来说非常适合.NET,但.NET Core没有 decimal.Round
方法。
在.NET Core中,我不得不使用:
decimal roundedValue = Math.Round(rawNumber, 2, MidpointRounding.AwayFromZero);
一种hacky方法,包括转换为字符串,是:
public string FormatTo2Dp(decimal myNumber)
{
// Use schoolboy rounding, not bankers.
myNumber = Math.Round(myNumber, 2, MidpointRounding.AwayFromZero);
return string.Format("{0:0.00}", myNumber);
}
https://msdn.microsoft。 COM / EN-US /库/ dwhawy9k%28V = vs.110%29.aspx
此链接详细说明了如何处理问题以及如果您想了解更多信息可以执行的操作。为简单起见,您要做的是
double whateverYouWantToChange = whateverYouWantToChange.ToString("F2");
如果您想要这种货币,可以通过输入“C2”来简化货币。而不是“F2”