使用字符串格式显示小数高达2处或简单的整数 [英] Using String Format to show decimal upto 2 places or simple integer

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

问题描述

我有一个价格字段中显示有时可以是100或100.99或100.9,我要的是在2位小数,显示的价格只有小数如果100,输入了这个价格,比如它shold只显示100 100.00不,如果价格是100.2它应该显示100.20同样为100.22应该是一样的。
我一派并在一些例子来了,但他们没有匹配正是我想要的:

  //只保留两位小数
的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我= DoFormat(123.0);

使用 DoFormat 是这样的:

 公共静态字符串DoFormat(双mynumber的)
{
    变种S =的String.Format({0:0.00},mynumber的);    如果(s.EndsWith(00))
    {
        回报((INT)为mynumber)的ToString();
    }
    其他
    {
        返回S;
    }
}

不优雅,但我在类似的情况在一些项目的工作。

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 shold 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 didnt 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"

解决方案

An inelegant way would be:

var my = DoFormat(123.0);

With DoFormat being something like:

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屋!

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