C# 如何将十进制值四舍五入到小数点后两位(用于页面上的输出)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/164926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I round a decimal value to 2 decimal places (for output on a page)
提问by wows
When displaying the value of a decimal currently with .ToString()
, it's accurate to like 15 decimal places, and since I'm using it to represent dollars and cents, I only want the output to be 2 decimal places.
当前使用 显示小数点的值时.ToString()
,精确到 15 位小数,并且由于我使用它来表示美元和美分,因此我只希望输出为 2 位小数。
Do I use a variation of .ToString()
for this?
我.ToString()
是否为此使用了变体?
采纳答案by albertein
decimalVar.ToString ("#.##"); // returns "" when decimalVar == 0
or
或者
decimalVar.ToString ("0.##"); // returns "0" when decimalVar == 0
回答by Jorge Ferreira
If you just need this for display use string.Format
如果你只需要这个来显示使用 string.Format
String.Format("{0:0.00}", 123.4567m); // "123.46"
http://www.csharp-examples.net/string-format-double/
http://www.csharp-examples.net/string-format-double/
The "m" is a decimal suffix. About the decimal suffix:
“m”是十进制后缀。关于十进制后缀:
回答by John Smith
回答by Hafthor
Given decimal d=12.345;the expressions d.ToString("C")or String.Format("{0:C}", d)yield $12.35- note that the current culture's currency settings including the symbol are used.
给定十进制 d=12.345;表达式d.ToString("C")或String.Format("{0:C}", d)产生$12.35- 请注意,使用了当前文化的货币设置,包括符号。
Note that "C"uses number of digits from current culture. You can always override default to force necessary precision with C{Precision specifier}
like String.Format("{0:C2}", 5.123d)
.
请注意,“C”使用当前文化中的位数。您始终可以使用C{Precision specifier}
like覆盖默认值以强制必要的精度String.Format("{0:C2}", 5.123d)
。
回答by Joel Mueller
If you want it formatted with commas as well as a decimal point (but no currency symbol), such as 3,456,789.12...
如果您希望它使用逗号和小数点(但没有货币符号)格式化,例如 3,456,789.12 ...
decimalVar.ToString("n2");
回答by Sofox
decimalVar.ToString("F");
This will:
这会:
- Round off to 2 decimal places eg.
23.456
→23.46
- Ensure that there
are always 2 decimal places eg.
23
→23.00
;12.5
→12.50
- 四舍五入到小数点后两位,例如。
23.456
→23.46
- 确保总是有 2 个小数位,例如。
23
→23.00
;12.5
→12.50
Ideal for displaying currency.
显示货币的理想选择。
Check out the documentation on ToString("F")(thanks to Jon Schneider).
查看关于ToString("F")的文档(感谢 Jon Schneider)。
回答by Mike M.
I know this is an old question, but I was surprised to see that no one seemed to post an answer that;
我知道这是一个老问题,但我很惊讶地发现似乎没有人发布答案;
- Didn't use bankers rounding
- Didn't keep the value as a decimal.
- 没有使用银行家四舍五入
- 没有将值保留为小数。
This is what I would use:
这就是我会使用的:
decimal.Round(yourValue, 2, MidpointRounding.AwayFromZero);
回答by Smitha Poluri
You can use system.globalization to format a number in any required format.
您可以使用 system.globalization 将数字格式化为任何所需的格式。
For example:
例如:
system.globalization.cultureinfo ci = new system.globalization.cultureinfo("en-ca");
If you have a decimal d = 1.2300000
and you need to trim it to 2 decimal places then it can be printed like this d.Tostring("F2",ci);
where F2 is string formating to 2 decimal places and ci is the locale or cultureinfo.
如果您有 adecimal d = 1.2300000
并且需要将其修剪为 2 个小数位,则可以像这样打印它d.Tostring("F2",ci);
,其中 F2 是字符串格式化为 2 个小数位,而 ci 是语言环境或文化信息。
for more info check this link
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
有关更多信息,请查看此链接
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
回答by Simon_Weaver
There's already two high scoring answers that refer to Decimal.Round(...) but I think a little more explanation is needed - because there's an unexpected important property of Decimal that isn't obvious.
已经有两个高分答案提到了 Decimal.Round(...) 但我认为需要更多的解释 - 因为 Decimal 有一个意想不到的重要属性并不明显。
A decimal 'knows' how many decimal places it has based upon where it came from.
小数根据它的来源“知道”它有多少个小数位。
For instance the following may be unexpected :
例如,以下可能是意料之外的:
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"
Doing the same operations with Double
will give no decimal places ("25"
) for each of the above.
执行相同的操作 withDouble
将不会"25"
为上述每个操作提供小数位 ( )。
When you want a decimal to 2 decimal places theres about a 95% chance it's because it's currency in which case this is probably fine for 95% of the time:
当你想要小数点到 2 个小数位时,大约有 95% 的机会是因为它是货币,在这种情况下,这在 95% 的情况下可能没问题:
Decimal.Parse("25.0").ToString("c") => ".00"
Or in XAML you just use {Binding Price, StringFormat=c}
或者在 XAML 中,您只需使用 {Binding Price, StringFormat=c}
One case I ran into where I needed a decimal AS a decimal was when sending XML to Amazon's webservice. The service was complaining because a Decimal value (originally from SQL Server) was being sent as 25.1200
and rejected, (25.12
was the expected format).
在将 XML 发送到亚马逊的网络服务时,我遇到了一个需要小数作为小数的情况。该服务抱怨是因为 Decimal 值(最初来自 SQL Server)被发送25.1200
并被拒绝,(25.12
是预期的格式)。
All I needed to do was Decimal.Round(...)
with 2 decimal places to fix the problem.
我需要做的就是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
is of type Decimal
so I couldn't just do ToString("N2")
and needed to round it and keep it as a decimal
.
TypedValue
是类型的,Decimal
所以我不能只做ToString("N2")
,需要将它四舍五入并将其保留为decimal
.
回答by Kaido
None of these did exactly what I needed, to force 2 d.p.and round up as 0.005 -> 0.01
这些都没有完全满足我的需要,强制2 dp并四舍五入为0.005 -> 0.01
Forcing 2 d.p. requires increasing the precision by 2 d.p. to ensure we have at least 2 d.p.
强制 2 dp 需要将精度提高 2 dp 以确保我们至少有 2 dp
then rounding to ensure we do not have more than 2 d.p.
然后四舍五入以确保我们没有超过 2 dp
Math.Round(exactResult * 1.00m, 2, MidpointRounding.AwayFromZero)
6.665m.ToString() -> "6.67"
6.6m.ToString() -> "6.60"