Remove trailing zeros

后端 未结 18 966
天命终不由人
天命终不由人 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:54

    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

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

    Use the hash (#) symbol to only display trailing 0's when necessary. See the tests below.

    decimal num1 = 13.1534545765;
    decimal num2 = 49.100145;
    decimal num3 = 30.000235;
    
    num1.ToString("0.##");       //13.15%
    num2.ToString("0.##");       //49.1%
    num3.ToString("0.##");       //30%
    
    0 讨论(0)
  • 2020-11-22 11:57

    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)

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

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

    This will work:

    decimal source = 2.4200m;
    string output = ((double)source).ToString();
    

    Or if your initial value is string:

    string source = "2.4200";
    string output = double.Parse(source).ToString();
    

    Pay attention to this comment.

    0 讨论(0)
  • 2020-11-22 12:03

    You can just set as:

    decimal decNumber = 23.45600000m;
    Console.WriteLine(decNumber.ToString("0.##"));
    
    0 讨论(0)
提交回复
热议问题