Decimal - truncate trailing zeros

后端 未结 3 1630
旧巷少年郎
旧巷少年郎 2020-12-18 19:48

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


        
相关标签:
3条回答
  • 2020-12-18 20:06

    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.

    0 讨论(0)
  • 2020-12-18 20:09

    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;
        }
    
    0 讨论(0)
  • 2020-12-18 20:28

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

    public static decimal Normalize(decimal value)
    {
        return value/1.000000000000000000000000000000000m;
    }
    
    0 讨论(0)
提交回复
热议问题