我有一个价格字段显示,有时可以是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"
当处理来自(T-)SQL数据库的小数时,您希望能够将可为空的小数和不可为空的小数转换为x位小数,并且能够根据表定义轻松地检查代码——当然,还要向用户显示正确的小数数量。
不幸的是,实体框架不能自动将SQL小数(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)
}
我不知道如何在格式说明符中放入一个条件,但你可以编写自己的格式化程序:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// all of these don't work
Console.WriteLine("{0:C}", 10);
Console.WriteLine("{0:00.0}", 10);
Console.WriteLine("{0:0}", 10);
Console.WriteLine("{0:0.00}", 10);
Console.WriteLine("{0:0}", 10.0);
Console.WriteLine("{0:0}", 10.1);
Console.WriteLine("{0:0.00}", 10.1);
// works
Console.WriteLine(String.Format(new MyFormatter(),"{0:custom}", 9));
Console.WriteLine(String.Format(new MyFormatter(),"{0:custom}", 9.1));
Console.ReadKey();
}
}
class MyFormatter : IFormatProvider, ICustomFormatter
{
public string Format(string format, object arg, IFormatProvider formatProvider)
{
switch (format.ToUpper())
{
case "CUSTOM":
if (arg is short || arg is int || arg is long)
return arg.ToString();
if (arg is Single || arg is Double)
return String.Format("{0:0.00}",arg);
break;
// Handle other
default:
try
{
return HandleOtherFormats(format, arg);
}
catch (FormatException e)
{
throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e);
}
}
return arg.ToString(); // only as a last resort
}
private string HandleOtherFormats(string format, object arg)
{
if (arg is IFormattable)
return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);
if (arg != null)
return arg.ToString();
return String.Empty;
}
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
return null;
}
}
}
最近的一个项目也有类似的需求。我写了这个十进制扩展法,
它使用货币(“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
为了让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);
我必须添加额外的转换(小数)来拥有Math。对两个十进制变量进行四舍五入比较。
如果其他答案都不适合你,这可能是因为你在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.##"/>