Remove trailing zeros

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

    A very low level approach, but I belive this would be the most performant way by only using fast integer calculations (and no slow string parsing and culture sensitive methods):

    public static decimal Normalize(this decimal d)
    {
        int[] bits = decimal.GetBits(d);
    
        int sign = bits[3] & (1 << 31);
        int exp = (bits[3] >> 16) & 0x1f;
    
        uint a = (uint)bits[2]; // Top bits
        uint b = (uint)bits[1]; // Middle bits
        uint c = (uint)bits[0]; // Bottom bits
    
        while (exp > 0 && ((a % 5) * 6 + (b % 5) * 6 + c) % 10 == 0)
        {
            uint r;
            a = DivideBy10((uint)0, a, out r);
            b = DivideBy10(r, b, out r);
            c = DivideBy10(r, c, out r);
            exp--;
        }
    
        bits[0] = (int)c;
        bits[1] = (int)b;
        bits[2] = (int)a;
        bits[3] = (exp << 16) | sign;
        return new decimal(bits);
    }
    
    private static uint DivideBy10(uint highBits, uint lowBits, out uint remainder)
    {
        ulong total = highBits;
        total <<= 32;
        total = total | (ulong)lowBits;
    
        remainder = (uint)(total % 10L);
        return (uint)(total / 10L);
    }
    

提交回复
热议问题