Remove trailing zeros

后端 未结 18 891
天命终不由人
天命终不由人 2020-11-22 11:26

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 t

相关标签:
18条回答
  • 2020-11-22 11:47

    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.
    
    0 讨论(0)
  • 2020-11-22 11:49

    try this code:

    string value = "100";
    value = value.Contains(".") ? value.TrimStart('0').TrimEnd('0').TrimEnd('.') : value.TrimStart('0');
    
    0 讨论(0)
  • 2020-11-22 11:51

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

    public static string DecimalToString(this decimal dec)
    {
        string strdec = dec.ToString(CultureInfo.InvariantCulture);
        return strdec.Contains(".") ? strdec.TrimEnd('0').TrimEnd('.') : strdec;
    }
    

    EDIT: using system CultureInfo.NumberFormat.NumberDecimalSeparator :

    public static string DecimalToString(this decimal dec)
    {
        string sep = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
        string strdec = dec.ToString(CultureInfo.CurrentCulture);
        return strdec.Contains(sep) ? strdec.TrimEnd('0').TrimEnd(sep.ToCharArray()) : strdec;
    }
    
    0 讨论(0)
  • 2020-11-22 11:51

    try like this

    string s = "2.4200";
    
    s = s.TrimStart('0').TrimEnd('0', '.');
    

    and then convert that to float

    0 讨论(0)
  • 2020-11-22 11:52

    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

    0 讨论(0)
  • 2020-11-22 11:54

    I ran into the same problem but in a case where I do not have control of the output to string, which was taken care of by a library. After looking into details in the implementation of the Decimal type (see http://msdn.microsoft.com/en-us/library/system.decimal.getbits.aspx), I came up with a neat trick (here as an extension method):

    public static decimal Normalize(this decimal value)
    {
        return value/1.000000000000000000000000000000000m;
    }
    

    The exponent part of the decimal is reduced to just what is needed. Calling ToString() on the output decimal will write the number without any trailing 0. E.g.

    1.200m.Normalize().ToString();
    
    0 讨论(0)
提交回复
热议问题