我有一个价格字段显示,有时可以是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"

当前回答

Try:

String.Format("{0:0.00}", Convert.ToDecimal(totalPrice));

其他回答

如果其他答案都不适合你,这可能是因为你在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"/>

Or

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

像这样的东西也可以:

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

试试这个:

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

简单的一行代码:

public static string DoFormat(double myNumber)
{
    return string.Format("{0:0.00}", myNumber).Replace(".00","");
}

try

double myPrice = 123.0;

String.Format(((Math.Round(myPrice) == myPrice) ? "{0:0}" : "{0:0.00}"), myPrice);