Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal - truncate trailing zeros

Tags:

c#

decimal

I noticed that .NET has some funky/unintuitive behavior when it comes to decimals and trailing zeros.

0m == 0.000m //true
0.1m == 0.1000m //true

but

(0m).ToString() == (0.000m).ToString() //false
(0.1m).ToString() == (0.1000m).ToString() //false

I know about necessity to comply to the ECMA CLI standard. However I would like to know if there is built-in way to truncate the trailing zeros for a decimal value without going through string representation (.ToString("G29") and parse back trick would work, but is neither fast nor elegant solution)?

Any ideas? Thanks a lot.

like image 838
Konrad Avatar asked Apr 26 '10 15:04

Konrad


People also ask

How do you get rid of trailing zeros after a decimal?

You can remove trailing zeros using TRIM() function.

What is the rule for trailing zeros?

To determine the number of significant figures in a number use the following 3 rules: Non-zero digits are always significant. Any zeros between two significant digits are significant. A final zero or trailing zeros in the decimal portion ONLY are significant.

Do trailing zeros count as decimal places?

If a zero is leading a number, before or after the decimal, it is not significant. E.g. 0.00849 - 3 significant figures. If a zero is trailing a non-zero digit, but it is not behind a decimal, it is not significant. E.g. 4500 - 2 significant figures.


3 Answers

I think that what you need is this (more details in my answer here) :

public static decimal Normalize(decimal value)
{
    return value/1.000000000000000000000000000000000m;
}
like image 89
Thomas Materna Avatar answered Oct 15 '22 02:10

Thomas Materna


Use a format string to specify the output of ToString():

(0.1m).ToString("0.#") -> "0.1"
(0.10000m).ToString("0.#") -> "0.1"

Use a "0" in the format to specify a digit or a non-significate 0, use "#" to specify a significant digit or suppress a a non-significate 0.

Edit: I assuming here that you are worried about the visual (string) representation of the number - if not, I will remove my answer.

like image 20
Ray Avatar answered Oct 15 '22 01:10

Ray


I don't like it much, but it works (for some range of values, at least)...

    static decimal Normalize(decimal value)
    {
        long div = 1;
        while(value - decimal.Truncate(value) != 0)
        {
            div *= 10;
            value *= 10;
        }
        if(div != 1) {
            value = (decimal)(long)value / div;
        }
        return value;
    }
like image 26
Marc Gravell Avatar answered Oct 15 '22 02:10

Marc Gravell