如何将小数值显示为小数点后2位?

当显示当前使用.ToString()的小数值时,它可以精确到小数点后15位,并且由于我使用它来表示美元和美分,我只希望输出为小数点后2位。

我是否为此使用.ToString()的变体?

1382592 次浏览
decimalVar.ToString("#.##"); // returns ".5" when decimalVar == 0.5m

decimalVar.ToString("0.##"); // returns "0.5"  when decimalVar == 0.5m

decimalVar.ToString("0.00"); // returns "0.50"  when decimalVar == 0.5m

如果您只需要此用于显示使用字符串。格式

String.Format("{0:0.00}", 123.4567m);      // "123.46"

http://www.csharp-examples.net/string-format-double/

“m”是十进制后缀。关于十进制后缀:

http://msdn.microsoft.com/en-us/library/364x0z75.aspx

给定十进制d=12.345;,表达式d. ToString("C")String. Format("{0: C}", d)//字符串格式产生12.35美元-请注意,使用了当前区域性的货币设置,包括符号。

请注意,“C”使用当前区域性的位数。您始终可以覆盖默认值以强制使用C{Precision specifier}String.Format("{0:C2}", 5.123d)一样的必要精度。

如果您希望它用逗号和小数点(但没有货币符号)格式化,例如3,456,789.12…

decimalVar.ToString("n2");
decimalVar.ToString("F");

这将:

  • 四舍五入到小数点后2位eg.23.45623.46
  • 确保有总是2位小数eg.2323.0012.512.50

非常适合显示货币。

查看ToString("F")的留档(感谢Jon Schneider)。

我知道这是一个古老的问题,但我很惊讶地看到,似乎没有人发布一个答案;

  1. 没有使用银行家四舍五入
  2. 将值保持为小数。

这就是我要使用的:

decimal.Round(yourValue, 2, MidpointRounding.AwayFromZero);

http://msdn.microsoft.com/en-us/library/9s0xa85y.aspx

您可以使用system.globalization以任何所需的格式格式化数字。

例如:

system.globalization.cultureinfo ci = new system.globalization.cultureinfo("en-ca");

如果您有一个decimal d = 1.2300000并且需要将其修剪为小数点后2位,那么它可以像这样打印d.Tostring("F2",ci);,其中F2是字符串格式为小数点后2位,ci是语言环境或文化信息。

更多信息请查看此链接
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

Decimal有一个非常重要的特征并不明显:

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%的时间可能是好的:

Decimal.Parse("25.0").ToString("c")     =>   "$25.00"

或者在XAML中,您将使用{Binding Price, StringFormat=c}

我遇到的一个需要十进制作为十进制的情况是在将XML发送到Amazon的Web服务时,该服务抱怨因为十进制值(最初来自SQLServer)作为25.1200发送并被拒绝(25.12是预期的格式)。

我所需要做的就是Decimal.Round(...)和2位小数来解决问题,而不管值的来源。

 // generated code by XSD.exeStandardPrice = new OverrideCurrencyAmount(){TypedValue = Decimal.Round(product.StandardPrice, 2),currency = "USD"}

TypedValue是类型Decimal,所以我不能只做ToString("N2"),需要将其舍入并保持为decimal

这些都没有完全满足我的需要,强制2 d. p.并将其四舍五入为0.005 -> 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"

这是一个小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.94742c: $2,345.950.00: 2345.950.##: 2345.95===================ToString: 43c: $43.000.00: 43.000.##: 43===================ToString: 0c: $0.000.00: 0.000.##: 0===================ToString: 0.007c: $0.010.00: 0.010.##: 0.01===================

https://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx

此链接详细解释了如何处理您的问题,以及如果您想了解更多信息,您可以做些什么。为了简单起见,您想做的是

double whateverYouWantToChange = whateverYouWantToChange.ToString("F2");

如果您想要这种货币,您可以通过键入“C2”而不是“F2”来使其更容易

Mike M.的回答对我来说是完美的。NET,但是. NET Core在撰写本文时没有decimal.Round方法。

在. NET Core中,我必须使用:

decimal roundedValue = Math.Round(rawNumber, 2, MidpointRounding.AwayFromZero);

一种hacky方法,包括转换为string,是:

public string FormatTo2Dp(decimal myNumber){// Use schoolboy rounding, not bankers.myNumber = Math.Round(myNumber, 2, MidpointRounding.AwayFromZero);
return string.Format("{0:0.00}", myNumber);}

如果值为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"));}
Double Amount = 0;string amount;amount=string.Format("{0:F2}", Decimal.Parse(Amount.ToString()));

如果您只需要保留2位小数(即切断所有其余的小数数字):

decimal val = 3.14789m;decimal result = Math.Floor(val * 100) / 100; // result = 3.14

如果你只需要保留小数点后3位:

decimal val = 3.14789m;decimal result = Math.Floor(val * 1000) / 1000; // result = 3.147
        var arr = new List<int>() { -4, 3, -9, 0, 4, 1 };decimal result1 = arr.Where(p => p > 0).Count();var responseResult1 = result1 / arr.Count();decimal result2 = arr.Where(p => p < 0).Count();var responseResult2 = result2 / arr.Count();decimal result3 = arr.Where(p => p == 0).Count();var responseResult3 = result3 / arr.Count();Console.WriteLine(String.Format("{0:#,0.000}", responseResult1));Console.WriteLine(String.Format("{0:#,0.0000}", responseResult2));Console.WriteLine(String.Format("{0:#,0.00000}", responseResult3));

你想放多少0就放多少。

最适用的解决方案是

decimalVar.ToString("#.##");