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
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
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%
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)
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
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.
You can just set as:
decimal decNumber = 23.45600000m;
Console.WriteLine(decNumber.ToString("0.##"));