我需要格式化号码,以便有一个逗号分隔条件上为任意数量的千位和包括大量如10000 10000变成一个万元9999 remaains为9999格式化用逗号
我想使用格式字符串来做到这一点,因为我不想测试数据以查看它的范围。
有谁知道如何做到这一点?
我需要格式化号码,以便有一个逗号分隔条件上为任意数量的千位和包括大量如10000 10000变成一个万元9999 remaains为9999格式化用逗号
我想使用格式字符串来做到这一点,因为我不想测试数据以查看它的范围。
有谁知道如何做到这一点?
格式字符串不能表现不同为不同的值,所以你能做的最好的是:
int n;
string s = n >= 10000 ? n.ToString("n0") : n.ToString("d");
(这将使用用户的文化,传递INumberFormatInfo
/CultureInfo
如果需要不同的文化)
num > 9999 ? num.ToString("N0", CultureInfo.InvariantCulture) : num.ToString();
“NO” 假设你不想d ecimals。 NFormat
我会建议创建自己的IFormatProvider具有快速长度检查和格式它与千位分隔符正常,如果是五个或更多字符,或无千位分隔符,如果是四个或更少的字符。
您可以轻松地修改MSDN docs on IFormatProvider中的示例。
必须在某个级别进行范围检查。如果实现像这样,可以嵌入的范围内的格式框架在一定程度内检查,绕过默认格式(包括组分隔符)如果所述数目少于5个数字:
class MyFormat : System.IFormatProvider, ICustomFormatter
{
#region IFormatProvider Members
public object GetFormat(Type formatType)
{
return this;
}
#endregion
#region ICustomFormatter Members
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (arg is double)
if (((double)arg >= 10000) || ((double)arg <= -10000))
return ((double)arg).ToString(format);
else
return ((double)arg).ToString("R");
if (arg is decimal)
if (((decimal)arg >= 10000) || ((decimal)arg <= -10000))
return ((decimal)arg).ToString(format);
else
return ((decimal)arg).ToString("R");
return arg.ToString();
}
#endregion
}
class Program
{
static MyFormat gFormat = new MyFormat();
static void Main(string[] args)
{
double dblVal1 = 9999, dblVal2 = 123456;
Console.WriteLine(String.Format(gFormat, "{0:N0} {1:N0}", dblVal1, dblVal2));
}
}
的OP明确规定他们“不想测试数据以查看它的范围”。不过,这是最明智的做法,所以+1。 – LukeH 2009-09-01 23:28:58
嗯......我认为我的解决方案更接近于尊重不需要进行范围检查的请求。 – BlueMonkMN 2009-09-02 00:02:25
顺便提一下,如果您除以正数,负数和零,您*可以*执行多种格式。看到这里:http://msdn.microsoft.com/en-us/library/0c899ak8.aspx#SectionSeparator你不能这样做除了那些部门。 – 2009-09-02 00:14:50