使用字符串格式化显示小数点后两位或简单整数

392

我有一个价格字段需要展示,有时候可能是100或100.99或100.9,我想要的是只有在输入了小数位的情况下才将价格显示为2位小数,例如如果价格是100,那么应该只显示100而不是100.00,如果价格是100.2,则应该显示100.20,对于100.22也是同样的。

我搜索了一些例子,但它们并不完全符合我的要求:

// just two decimal places
String.Format("{0:0.00}", 123.4567);      // "123.46"
String.Format("{0:0.00}", 123.4);         // "123.40"
String.Format("{0:0.00}", 123.0);         // "123.00"

4
可能是与 .net 将十进制格式化为两位小数或整数 相似的问题。 - Binary Worrier
2
回复:“我的要求是,仅在输入价格的小数时显示2位小数”——因此,如果用户键入“100.00”,您希望显示“100.00”,但如果他们键入“100”,您只想显示“100”?——数字类型仅跟踪数字的值——而不是用户输入的哪些无关紧要的数字和哪些不是——为此,您需要使用字符串。 - BrainSlugs83
2
@BinaryWorrier 我认为这个问题可能是一个重复的,但它有更好和更完整的答案。在我看来,另一个应该被标记为这个的重复。 - Ryan Gates
3
只需添加.Replace(".00","") - Dave Sumter
3
你只需要使用 value.ToString("0.##"); 即可。 - Mehdi
显示剩余2条评论
18个回答

5

恐怕没有内置的格式可以做到这一点。根据值是整数还是小数,您将不得不使用不同的格式。或者始终格式化为2位小数,并在之后操作字符串以删除任何尾随的“.00”。


5

试试这个:

var number = 123.4567;
var str = number.ToString("N2");

感谢您的推荐@help-info.de,没错 :) - Sepideh I
对我来说,这将值100显示为100.00,这不是OP想要的。 - Joe Strout

4
如果其他答案都不适用于您,可能是因为您正在OnLoad函数中绑定控件的ContentProperty,这意味着这种方法不起作用:
private void UserControl_Load(object sender, RoutedEventArgs e)
{
  Bind.SetBindingElement(labelName, String.Format("{0:0.00}", PropertyName), Label.ContentProperty) 
}

解决方案很简单:在XAML中有一个名为ContentStringFormat的属性。因此,当您创建标签时,请执行以下操作:
//if you want the decimal places definite
<Label Content="0" Name="labelName" ContentStringFormat="0.00"/>

或者

//if you want the decimal places to be optional
<Label Content="0" Name="labelName" ContentStringFormat="0.##"/>

3

类似这样的内容也可以正常工作:

String.Format("{0:P}", decimal.Parse(Resellers.Fee)).Replace(".00", "")

那会给出一个百分比吗? - user2761580

3
处理来自(T)SQL数据库的小数时,您需要能够转换可空和非可空小数,并能轻松地根据表定义查看代码,并且当然,向用户显示正确数量的小数位。
不幸的是,实体框架不能自动将类似于 SQL decimal(18,2) 的内容转换为具有相同小数位数的.NET等效内容(因为只有具有完整精度的小数可用)。 您必须手动截断小数位数。
所以,我是这样做的:
public static class Extensions
{
    public static string ToStringDecimal(this decimal d, byte decimals)
    {
        var fmt = (decimals>0) ? "0." + new string('0', decimals) : "0";
        return d.ToString(fmt);
    }

    public static string ToStringDecimal(this decimal? d, byte decimals)
    {
        if (!d.HasValue) return "";
        return ToStringDecimal(d.Value, decimals);
    }
}

使用示例:

void Main()
{
    decimal d = (decimal)1.2345;
    decimal? d2 = null; 

    Console.WriteLine(d.ToStringDecinal(2)); // prints: "1.23" (2 decimal places)
    Console.WriteLine(d.ToStringDecinal(0)); // prints: "1" (show integer number)
    Console.WriteLine(d2.ToStringDecimal(2)); // prints: "" (show null as empty string)
}

2
为了让Kahia编写的代码更加清晰(虽然它已经很清晰,但当你想添加更多文本时就会变得棘手)...尝试这个简单的解决方案。
if (Math.Round((decimal)user.CurrentPoints) == user.CurrentPoints)
     ViewBag.MyCurrentPoints = String.Format("Your current Points: {0:0}",user.CurrentPoints);
else
     ViewBag.MyCurrentPoints = String.Format("Your current Points: {0:0.0}",user.CurrentPoints);

我不得不添加额外的转换(decimal),才能让Math.Round比较这两个十进制变量。


1
最近的一个项目有类似的需求。我编写了这个十进制扩展方法,它使用 货币 ("C") 格式说明符。除了去掉零之外,它还具有十进制位精度、货币符号、分隔符和文化等选项。
public static DecimalExtension{

     public static string ToCurrency(this decimal val, 
                                     int precision = 2, 
                                     bool currencySymbol = false, 
                                     bool separator = false, 
                                     CultureInfo culture = null)
      {     
         if(culture == null) culture = new CultureInfo("en-US");
                                                   
         NumberFormatInfo nfi = culture.NumberFormat;
         nfi.CurrencyDecimalDigits = precision;
            
         string zeros = new String('0', precision);       
                    
         //Remove zeros
         var result = val.ToString("C",fi).Replace(nfi.CurrencyDecimalSeparator + zeros,"");
                     
         if(!separator) result = result.Replace(nfi.CurrencyGroupSeparator,"");
                    
         return currencySymbol? result: result.Replace(nfi.CurrencySymbol,"");      
        }   
}

例子:

decimal Total = 123.00M;
Console.WriteLine(Total.ToCurrency());  
//output: 123

decimal Total = 1123.12M;
Console.WriteLine(Total.ToCurrency()); 
//Output:  1123.12

Console.WriteLine(Total.ToCurrency(4));
//Output:  1123.1200

Console.WriteLine(Total.ToCurrency(2,true,true));
//output:  $1,123.12
 
CultureInfo culture = new CultureInfo("pt-BR")  //Brazil
Console.WriteLine(Total.ToCurrency(2,true,true, culture));
//output:  R$ 1.123,12

-1

试一试

string Output = String.Format("{0:0.00}", Decimal.Parse(InputStringValue));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接