Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a decimal without trailing zeros

I've just learned that a decimal somehow remembers how much trailaing zero's were needed to store a number. With other words: it remembers the size of the fraction.

For example:

123M.ToString() ==> resuls in: 123
123.00M.ToString() ==> resuls in: 123.00
123.450M.ToString() ==> resuls in: 123.450

I am looking for a formatting string or another trick to get rid of those "unneeded" trailing zeros, but keeping the significant digits. So:

123M.ToString() ==> resuls in: 123
123.00M.ToString() ==> resuls in: 123
123.450M.ToString() ==> resuls in: 123.45

Removing the zeros at the end of the new string is not a real option for me, because then I have to find out if the string contains a fraction and if so, also have to remove the optional '.' or ',' depending on the culture, etc.

like image 678
Martin Mulder Avatar asked Jul 07 '13 21:07

Martin Mulder


People also ask

How do you get rid of trailing zero in decimals?

Use the :: operator to convert a decimal number containing trailing zeros to a number without additional zeros. This operator converts the value on the left to the data type placed on the right.

How do you remove floating trailing zeros?

To remove the trailing zeros from a number, pass the number to the parseFloat() function. The parseFloat function parses the provided value, returning a floating point number, which automatically removes any trailing zeros.

Should you have a trailing zero after a decimal point?

Trailing zeros (the right most zeros) are significant when there is a decimal point in the number. For this reason it is important to give consideration to when a decimal point is used and to keep the trailing zeros to indicate the actual number of significant figures.


1 Answers

There are several ways to do it, but since you are converting to a String object anyway, I suppose you could try something like this:

myDecimalVariable.ToString("G29");

or, using your code above, assuming 123.00M is your decimal:

123.00M.ToString("G29");

Here is the explanation of how that concise example works:

The G format with a number means to format that many significant digits. Because 29 is the most significant digits that a Decimal can have, this will effectively truncate the trailing zeros without rounding.

like image 74
Michael Hawkins Avatar answered Oct 07 '22 07:10

Michael Hawkins