使用字符串格式最多显示两位小数或简单整数 [英] Using String Format to show decimal up to 2 places or simple integer

查看:96
本文介绍了使用字符串格式最多显示两位小数或简单整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要显示的价格字段,有时可以是100或100.99或100.9,我要显示的是仅在为该价格输入小数后才在2个小数位显示价格,例如,如果该价格为100,它应该只显示100而不是100.00,如果价格是100.2,则应该显示100.20,而100.22应该相同。
我用Google搜索并遇到了一些示例,但它们与我想要的不完全匹配:

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.

这篇关于使用字符串格式最多显示两位小数或简单整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆