Remove trailing zeros

2018-12-31 18:01发布

I have some fields returned by a collection as

2.4200
2.0044
2.0000

I want results like

2.42
2.0044
2

I tried with String.Format, but it returns 2.0000 and setting it to N0 rounds the other values as well.

标签: c# .net decimal
16条回答
一个人的天荒地老
2楼-- · 2018-12-31 18:44

In case you want to keep decimal number, try following example:

number = Math.Floor(number * 100000000) / 100000000;
查看更多
梦寄多情
3楼-- · 2018-12-31 18:45

You can just set as:

decimal decNumber = 23.45600000m;
Console.WriteLine(decNumber.ToString("0.##"));
查看更多
与风俱净
4楼-- · 2018-12-31 18:47

Very simple answer is to use TrimEnd(). Here is the result,

double value = 1.00;
string output = value.ToString().TrimEnd('0');

Output is 1 If my value is 1.01 then my output will be 1.01

查看更多
荒废的爱情
5楼-- · 2018-12-31 18:50

I use this code to avoid "G29" scientific notation:

public static string DecimalToString(decimal dec)
{
    string strdec = dec.ToString(CultureInfo.InvariantCulture);
    return strdec.Contains(".") ? strdec.TrimEnd('0').TrimEnd('.') : strdec;
}
查看更多
登录 后发表回答