使用字符串格式显示最多 2 位小数或简单整数 [英] Using String Format to show decimal up to 2 places or simple integer
问题描述
我有一个要显示的价格字段,有时可以是 100 或 100.99 或 100.9,我想要的是仅在为该价格输入小数位时以 2 位小数显示价格,例如,如果它是 100它应该只显示 100 而不是 100.00,如果价格是 100.2,它应该同样显示 100.20,因为 100.22 应该是一样的.我用谷歌搜索并发现了一些示例,但它们与我想要的不完全匹配:
I have got a price field to display which sometimes can be either 100 or 100.99 or 100.9, What I want is to display the price in 2 decimal places only if the decimals are entered for that price , for instance if its 100 so it should only show 100 not 100.00 and if the price is 100.2 it should display 100.20 similarly for 100.22 should be same . I googled and came across some examples but they didn't match exactly what i wanted :
// 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"
推荐答案
不雅的方式是:
var my = DoFormat(123.0);
DoFormat
类似于:
public static string DoFormat( double myNumber )
{
var s = string.Format("{0:0.00}", myNumber);
if ( s.EndsWith("00") )
{
return ((int)myNumber).ToString();
}
else
{
return s;
}
}
不优雅,但在某些项目的类似情况下对我有用.
Not elegant but working for me in similar situations in some projects.
这篇关于使用字符串格式显示最多 2 位小数或简单整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!