简体   繁体   English

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

[英]How do I display a decimal value to 2 decimal places?

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 位,并且由于我用它来表示美元和美分,所以我只希望 output 为小数点后 2 位。

Do I use a variation of .ToString() for this?我是否为此使用.ToString()的变体?

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

or或者

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

or或者

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

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. Keeps the value as a decimal.将值保留为小数。

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

decimalVar.ToString("F");

This will:这会:

  • Round off to 2 decimal places eg.四舍五入到小数点后两位,例如。 23.45623.46 23.45623.46
  • Ensure that there are always 2 decimal places eg.确保总是有 2 个小数位,例如。 2323.00 ; 2323.00 12.512.50 12.512.50

Ideal for displaying currency.显示货币的理想选择。

Check out the documentation on ToString("F") (thanks to Jon Schneider).查看关于ToString("F")的文档(感谢 Jon Schneider)。

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. “m”是十进制后缀。 About the decimal suffix:关于十进制后缀:

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

Given decimal d=12.345;给定十进制 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.ToString("C")String.Format("{0:C}", d)产生$12.35 - 请注意,使用了当前文化的货币设置,包括符号。

Note that "C" uses number of digits from current culture.请注意, “C”使用当前文化中的位数。 You can always override default to force necessary precision with C{Precision specifier} like String.Format("{0:C2}", 5.123d) .您始终可以覆盖默认值以使用C{Precision specifier}强制必要的精度,例如String.Format("{0:C2}", 5.123d)

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

decimalVar.ToString("n2");

There's a very important characteristic of Decimal that isn't obvious: Decimal有一个非常重要的特征,但并不明显:

A Decimal 'knows' how many decimal places it has based upon where it came from Decimal根据它的来源“知道”它有多少个小数位

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 result in zero decimal places ( "25" ) for all of the above examples.对于上述所有示例,对Double执行相同的操作将导致小数点为零( "25" )。

If you want a decimal to 2 decimal places there's a high likelyhood it's because it's currency in which case this is probably fine for 95% of the time:如果你想要小数点到 2 位小数,很有可能是因为它是货币,在这种情况下,这在 95% 的情况下可能没问题:

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

Or in XAML you would 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.在将 XML 发送到亚马逊的网络服务时,我遇到了一个需要小数作为小数的情况。 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).该服务抱怨是因为 Decimal 值(最初来自 SQL Server)作为25.1200被发送25.1200拒绝( 25.12是预期的格式)。

All I needed to do was Decimal.Round(...) with 2 decimal places to fix the problem regardless of the source of the value.我需要做的就是Decimal.Round(...) 2 个小数位的Decimal.Round(...)来解决问题,而不管值的来源如何。

 // 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 . TypedValueDecimal类型,所以我不能只做ToString("N2")并且需要将它四舍五入并将其保留为decimal

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
===================

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 分钟时间。

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. Mike M. 的答案在 .NET 上对我来说是完美的,但在撰写本文时,.NET Core 没有decimal.Round方法。

In .NET Core, I had to use:在 .NET Core 中,我不得不使用:

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

None of these did exactly what I needed, to force 2 dp and round up as 0.005 -> 0.01这些都没有完全满足我的需要,强制2 dp并四舍五入为0.005 -> 0.01

Forcing 2 dp requires increasing the precision by 2 dp to ensure we have at least 2 dp强制 2 dp 需要将精度提高 2 dp 以确保我们至少有 2 dp

then rounding to ensure we do not have more than 2 dp然后四舍五入以确保我们没有超过 2 dp

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

6.665m.ToString() -> "6.67"

6.6m.ToString() -> "6.60"

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

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);如果你有一个decimal d = 1.2300000并且你需要把它修整到 2 个小数位,那么它可以像这样打印d.Tostring("F2",ci); where F2 is string formating to 2 decimal places and ci is the locale or cultureinfo.其中 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

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”来让它更容易

The most applicable solution is最适用的解决方案是

decimalVar.ToString("#.##");
Double Amount = 0;
string amount;
amount=string.Format("{0:F2}", Decimal.Parse(Amount.ToString()));

If you need to keep only 2 decimal places (ie cut off all the rest of decimal digits):如果您只需要保留 2 个小数位(即截掉所有其余的小数位):

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

If you need to keep only 3 decimal places:如果您只需要保留 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));

you can put as many 0 as you want.你可以放任意多个 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM