繁体   English   中英

C# Double - ToString() 格式有两位小数但没有四舍五入

[英]C# Double - ToString() formatting with two decimal places but no rounding

如何在 C# 中将Double格式化为String以便只有两位小数?

如果我使用String.Format("{0:0.00}%", myDoubleValue)然后对数字进行四舍五入,我想要一个没有任何四舍五入的简单截断。 我还希望转换为String是文化敏感的。

我使用以下内容:

double x = Math.Truncate(myDoubleValue * 100) / 100;

例如:

如果号码是 50.947563 并且您使用以下内容,则会发生以下情况:

- Math.Truncate(50.947563 * 100) / 100;
- Math.Truncate(5094.7563) / 100;
- 5094 / 100
- 50.94

你的答案被截断了,现在要格式化字符串,只需执行以下操作:

string s = string.Format("{0:N2}%", x); // No fear of rounding and takes the default number format

由于.## ,以下四舍五入数字,但只显示最多 2 个小数位(删除任何尾随零)。

decimal d0 = 24.154m;
decimal d1 = 24.155m;
decimal d2 = 24.1m;
decimal d3 = 24.0m;

d0.ToString("0.##");   //24.15
d1.ToString("0.##");   //24.16 (rounded up)
d2.ToString("0.##");   //24.1  
d3.ToString("0.##");   //24

http://dobrzanski.net/2009/05/14/c-decimaltostring-and-how-to-get-rid-of-trailing-zeros/

我建议你先截断,然后格式化:

double a = 123.4567;
double aTruncated = Math.Truncate(a * 100) / 100;
CultureInfo ci = new CultureInfo("de-DE");
string s = string.Format(ci, "{0:0.00}%", aTruncated);

使用常量 100 截断 2 位数字; 使用 1 后跟与您想要的小数点后的数字一样多的零。 使用您需要的区域性名称来调整格式结果。

我使用price.ToString("0.00")获取前导 0

最简单的方法,使用数字格式字符串:

double total = "43.257"
MessageBox.Show(total.ToString("F"));

添加一个额外的小数如何四舍五入然后丢弃:

var d = 0.241534545765;
var result1 = d.ToString("0.###%");

var result2 = result1.Remove(result1.Length - 1);

由 Kyle Rozendo 表示的 c# 函数:

string DecimalPlaceNoRounding(double d, int decimalPlaces = 2)
{
    double factor = Math.Pow(10, decimalPlaces);
    d = d * factor;
    d = Math.Truncate(d);
    d = d / factor;
    return string.Format("{0:N" + Math.Abs(decimalPlaces) + "}", d);
}

这对我有用

string prouctPrice = Convert.ToDecimal(String.Format("{0:0.00}", Convert.ToDecimal(yourString))).ToString();

我在 Xamarin Forms 上遇到了这个问题,并通过以下方式解决了这个问题:

percent.ToString("0.##"+"%")

我知道这是一个旧线程,但我只是不得不这样做。 虽然这里的其他方法有效,但我想要一种简单的方法来影响对string.format的大量调用。 因此,将Math.Truncate添加到所有调用中并不是一个好的选择。 此外,由于某些格式存储在数据库中,因此情况变得更糟。

因此,我制作了一个自定义格式提供程序,它允许我向格式字符串添加截断,例如:

string.format(new FormatProvider(), "{0:T}", 1.1299); // 1.12
string.format(new FormatProvider(), "{0:T(3)", 1.12399); // 1.123
string.format(new FormatProvider(), "{0:T(1)0,000.0", 1000.9999); // 1,000.9

实现非常简单,很容易扩展到其他需求。

public class FormatProvider : IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof (ICustomFormatter))
        {
            return this;
        }
        return null;
    }

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        if (arg == null || arg.GetType() != typeof (double))
        {
            try
            {
                return HandleOtherFormats(format, arg);
            }
            catch (FormatException e)
            {
                throw new FormatException(string.Format("The format of '{0}' is invalid.", format));
            }
        }

        if (format.StartsWith("T"))
        {
            int dp = 2;
            int idx = 1;
            if (format.Length > 1)
            {
                if (format[1] == '(')
                {
                    int closeIdx = format.IndexOf(')');
                    if (closeIdx > 0)
                    {
                        if (int.TryParse(format.Substring(2, closeIdx - 2), out dp))
                        {
                            idx = closeIdx + 1;
                        }
                    }
                    else
                    {
                        throw new FormatException(string.Format("The format of '{0}' is invalid.", format));
                    }
                }
            }
            double mult = Math.Pow(10, dp);
            arg = Math.Truncate((double)arg * mult) / mult;
            format = format.Substring(idx);
        }

        try
        {
            return HandleOtherFormats(format, arg);
        }
        catch (FormatException e)
        {
            throw new FormatException(string.Format("The format of '{0}' is invalid.", format));
        }
    }

    private string HandleOtherFormats(string format, object arg)
    {
        if (arg is IFormattable)
        {
            return ((IFormattable) arg).ToString(format, CultureInfo.CurrentCulture);
        }
        return arg != null ? arg.ToString() : String.Empty;
    }
}

为了什么是值得的,为了显示货币,你可以使用"C"

double cost = 1.99;
m_CostText.text = cost.ToString("C"); /*C: format as currentcy */

输出: $1.99

您也可以编写自己的IFormatProvider ,但我想最终您必须想出一种方法来进行实际的截断。

.NET Framework 还支持自定义格式。 这通常涉及创建实现 IFormatProvider 和ICustomFormatter的格式设置类。 (msdn)

至少它很容易重复使用。

CodeProject 上有一篇关于如何实现您自己的 IFormatProvider/ICustomFormatter 的文章。 在这种情况下,“扩展”现有的数字格式可能是最好的选择。 看起来并不太难。

以下只能用于使用 String .. 属性的显示。

double value = 123.456789;
String.Format("{0:0.00}", value);

解决方案:

var d = 0.123345678; 
var stringD = d.ToString(); 
int indexOfP = stringD.IndexOf("."); 
var result = stringD.Remove((indexOfP+1)+2);

(indexOfP+1)+2(这个数字取决于你想保留多少个数字。我给它两个因为问题所有者想要。)

还要注意系统的CultureInformation 这里我的解决方案没有四舍五入。

在此示例中,您只需将变量MyValue定义为 double。 因此,您将在字符串变量NewValue 中获得格式化的值。

注意 - 还要设置 C# using 语句:

using System.Globalization;  

string MyFormat = "0";
if (MyValue.ToString (CultureInfo.InvariantCulture).Contains (CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator))
   {
      MyFormat += ".00";
   }

string NewValue = MyValue.ToString(MyFormat);

暂无
暂无

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

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