如何将十进制值圆到小数点后两位(用于页面上的输出)

时间:2020-12-25 11:10:13

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()的变体吗?

15 个解决方案

#1


692  

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

or

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

#2


489  

I know this is an old question, but I was surprised to see that no one seemed to post an answer that;

我知道这是一个老问题,但我很惊讶地发现,似乎没有人回答这个问题;

  1. Didn't use bankers rounding
  2. 没有使用银行家舍入
  3. Didn't keep the value as a decimal.
  4. 没有把值保留为小数。

This is what I would use:

这就是我要用的:

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

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

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

#3


261  

decimalVar.ToString("F");

This will:

这将:

Round off to 2 decimal places eg. 23.456 => 23.46

四舍五入到小数点后两位。23.456 = > 23.46

Ensure that there are always 2 decimal places eg. 23 => 23.00, 12.5 => 12.50

确保总是有2个小数点。23 => 23.00,12.5 => 12.50。

Ideal for currency and displaying monetary amounts.

理想的货币和显示货币数量。

#4


92  

If you just need this for display use 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”是一个十进制的后缀。关于小数后缀:

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

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

#5


53  

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”)或字符串。格式(“{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{精度指示符}字符串。格式(“{ 0:C2 }”,5.123 d)。

#6


40  

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");

#7


26  

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.

已经有两个高得分的答案可以参考十进制。(…)但是我认为需要更多的解释——因为有一个意想不到的重要的小数属性,它并不明显。

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.

做相同的操作,Double将不会给上面的每一个小数位数(“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:

当你想要小数点后两位小数的概率是95%因为在95%的情况下这很可能是正确的

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

Or in XAML you just use {Binding Price, StringFormat=c}

或者在XAML中使用{绑定价格,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发送到Amazon的webservice时。该服务正在抱怨,因为一个十进制值(最初来自SQL Server)被发送为25.1200并且被拒绝,(25.12是期望的格式)。

All I needed to do was Decimal.Round(...) with 2 decimal places to fix the problem.

我所需要做的就是把小数点拿下来,用小数点后两位来解决这个问题。

 // 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”),需要绕过它,并将它保持为小数。

#8


18  

Here is a little Linqpad program to show different formats:

这里有一个小的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("===================");
}

Here are the results:

这里是结果:

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: $0.00
0.00: 0.00
0.##: 0
===================
ToString: 0.007
c: $0.01
0.00: 0.01
0.##: 0.01
===================

#9


14  

Math.Round Method (Decimal, Int32)

数学。圆的方法(小数,Int32)

#10


9  

None of these did exactly what I needed, to force 2 d.p. and round up as 0.005 -> 0.01

所有这些都没有达到我所需要的,迫使2。p和0。005 ->。01。

Forcing 2 d.p. requires increasing the precision by 2 d.p. to ensure we have at least 2 d.p.

强迫2 d.p需要增加2 d的精度,以确保我们至少有2个d。p。

then rounding to ensure we do not have more than 2 d.p.

然后四舍五入确保我们没有超过2。p。

Math.Round(exactResult * 1.00m, 2, MidpointRounding.AwayFromZero)

6.665m.ToString() -> "6.67"

6.6m.ToString() -> "6.60"

#11


7  

You can use system.globalization to format a number in any required format.

您可以使用系统。全球化以任何必需的格式格式化数字。

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.

如果你有一个小数d = 1。2300000,你需要把它修到小数点后2位,那么它就可以像这样打印出来了。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。

#12


5  

The top-rated answer describes a method for formatting the string representation of the decimal value, and it works.

最*的答案描述了一种方法,用于格式化十进制值的字符串表示形式,它可以工作。

However, if you actually want to change the precision saved to the actual value, you need to write something like the following:

但是,如果您实际想要更改保存到实际值的精度,则需要编写如下内容:

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;
    }
}

An example unit test:

一个示例单元测试:

[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"));
}

#13


4  

Very rarely would you want an empty string if the value is 0.

如果值为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"

The top rated answer is incorrect and has wasted 10 minutes of (most) people's time.

排名第一的答案是错误的,浪费了人们10分钟的时间。

#14


4  

Mike M.'s answer was perfect for me on .NET, but .NET Core doesn't have a decimal.Round method at the time of writing.

迈克·M。在。net中,我的答案是完美的,但是。net核心没有十进制。在写作时采用圆法。

In .NET Core, I had to use:

在。net核心中,我必须使用:

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

A hacky method, including conversion to string, is:

一个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);
}

#15


3  

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

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

This link explains in detail how you can handle your problem and what you can do if you want to learn more. For simplicity purposes, what you want to do is

这个链接详细解释了你如何处理你的问题,如果你想了解更多,你可以做什么。为了简单起见,您需要做的是。

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

if you want this for a currency, you can make it easier by typing "C2" instead of "F2"

如果你想要这种货币,你可以通过键入“C2”而不是“F2”来简化它

#1


692  

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

or

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

#2


489  

I know this is an old question, but I was surprised to see that no one seemed to post an answer that;

我知道这是一个老问题,但我很惊讶地发现,似乎没有人回答这个问题;

  1. Didn't use bankers rounding
  2. 没有使用银行家舍入
  3. Didn't keep the value as a decimal.
  4. 没有把值保留为小数。

This is what I would use:

这就是我要用的:

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

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

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

#3


261  

decimalVar.ToString("F");

This will:

这将:

Round off to 2 decimal places eg. 23.456 => 23.46

四舍五入到小数点后两位。23.456 = > 23.46

Ensure that there are always 2 decimal places eg. 23 => 23.00, 12.5 => 12.50

确保总是有2个小数点。23 => 23.00,12.5 => 12.50。

Ideal for currency and displaying monetary amounts.

理想的货币和显示货币数量。

#4


92  

If you just need this for display use 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”是一个十进制的后缀。关于小数后缀:

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

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

#5


53  

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”)或字符串。格式(“{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{精度指示符}字符串。格式(“{ 0:C2 }”,5.123 d)。

#6


40  

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");

#7


26  

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.

已经有两个高得分的答案可以参考十进制。(…)但是我认为需要更多的解释——因为有一个意想不到的重要的小数属性,它并不明显。

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.

做相同的操作,Double将不会给上面的每一个小数位数(“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:

当你想要小数点后两位小数的概率是95%因为在95%的情况下这很可能是正确的

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

Or in XAML you just use {Binding Price, StringFormat=c}

或者在XAML中使用{绑定价格,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发送到Amazon的webservice时。该服务正在抱怨,因为一个十进制值(最初来自SQL Server)被发送为25.1200并且被拒绝,(25.12是期望的格式)。

All I needed to do was Decimal.Round(...) with 2 decimal places to fix the problem.

我所需要做的就是把小数点拿下来,用小数点后两位来解决这个问题。

 // 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”),需要绕过它,并将它保持为小数。

#8


18  

Here is a little Linqpad program to show different formats:

这里有一个小的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("===================");
}

Here are the results:

这里是结果:

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: $0.00
0.00: 0.00
0.##: 0
===================
ToString: 0.007
c: $0.01
0.00: 0.01
0.##: 0.01
===================

#9


14  

Math.Round Method (Decimal, Int32)

数学。圆的方法(小数,Int32)

#10


9  

None of these did exactly what I needed, to force 2 d.p. and round up as 0.005 -> 0.01

所有这些都没有达到我所需要的,迫使2。p和0。005 ->。01。

Forcing 2 d.p. requires increasing the precision by 2 d.p. to ensure we have at least 2 d.p.

强迫2 d.p需要增加2 d的精度,以确保我们至少有2个d。p。

then rounding to ensure we do not have more than 2 d.p.

然后四舍五入确保我们没有超过2。p。

Math.Round(exactResult * 1.00m, 2, MidpointRounding.AwayFromZero)

6.665m.ToString() -> "6.67"

6.6m.ToString() -> "6.60"

#11


7  

You can use system.globalization to format a number in any required format.

您可以使用系统。全球化以任何必需的格式格式化数字。

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.

如果你有一个小数d = 1。2300000,你需要把它修到小数点后2位,那么它就可以像这样打印出来了。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。

#12


5  

The top-rated answer describes a method for formatting the string representation of the decimal value, and it works.

最*的答案描述了一种方法,用于格式化十进制值的字符串表示形式,它可以工作。

However, if you actually want to change the precision saved to the actual value, you need to write something like the following:

但是,如果您实际想要更改保存到实际值的精度,则需要编写如下内容:

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;
    }
}

An example unit test:

一个示例单元测试:

[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"));
}

#13


4  

Very rarely would you want an empty string if the value is 0.

如果值为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"

The top rated answer is incorrect and has wasted 10 minutes of (most) people's time.

排名第一的答案是错误的,浪费了人们10分钟的时间。

#14


4  

Mike M.'s answer was perfect for me on .NET, but .NET Core doesn't have a decimal.Round method at the time of writing.

迈克·M。在。net中,我的答案是完美的,但是。net核心没有十进制。在写作时采用圆法。

In .NET Core, I had to use:

在。net核心中,我必须使用:

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

A hacky method, including conversion to string, is:

一个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);
}

#15


3  

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

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

This link explains in detail how you can handle your problem and what you can do if you want to learn more. For simplicity purposes, what you want to do is

这个链接详细解释了你如何处理你的问题,如果你想了解更多,你可以做什么。为了简单起见,您需要做的是。

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

if you want this for a currency, you can make it easier by typing "C2" instead of "F2"

如果你想要这种货币,你可以通过键入“C2”而不是“F2”来简化它