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:26

try this code:

string value = "100";
value = value.Contains(".") ? value.TrimStart('0').TrimEnd('0').TrimEnd('.') : value.TrimStart('0');
查看更多
步步皆殇っ
3楼-- · 2018-12-31 18:27

I found an elegant solution from http://dobrzanski.net/2009/05/14/c-decimaltostring-and-how-to-get-rid-of-trailing-zeros/

Basically

decimal v=2.4200M;

v.ToString("#.######"); // Will return 2.42. The number of # is how many decimal digits you support.

查看更多
爱死公子算了
4楼-- · 2018-12-31 18:27

Depends on what your number represents and how you want to manage the values: is it a currency, do you need rounding or truncation, do you need this rounding only for display?

If for display consider formatting the numbers are x.ToString("")

http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx and

http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

If it is just rounding, use Math.Round overload that requires a MidPointRounding overload

http://msdn.microsoft.com/en-us/library/ms131274.aspx)

If you get your value from a database consider casting instead of conversion: double value = (decimal)myRecord["columnName"];

查看更多
永恒的永恒
5楼-- · 2018-12-31 18:28

The following code could be used to not use the string type:

int decimalResult = 789.500
while (decimalResult>0 && decimalResult % 10 == 0)
{
    decimalResult = decimalResult / 10;
}
return decimalResult;

Returns 789.5

查看更多
几人难应
6楼-- · 2018-12-31 18:35

In my opinion its safer to use Custom Numeric Format Strings.

decimal d = 0.00000000000010000000000m;
string custom = d.ToString("0.#########################");
// gives: 0,0000000000001
string general = d.ToString("G29");
// gives: 1E-13
查看更多
零度萤火
7楼-- · 2018-12-31 18:36

Truncate trailing Zeros is very easy, resolve with a duplex cast:

        decimal mydecimal = decimal.Parse("1,45000000"); //(I)
        decimal truncate = (decimal)(double)mydecimal;   //(II)

(I) --> Parse decimal value from any string source.

(II) --> First: Cast to double this remove the trailing zeros. Second: Other cast to decimal because dont exist implicit conversion from decimal to double and viceversa)

查看更多
登录 后发表回答