Get number of digits before decimal point

前端 未结 25 1947
独厮守ぢ
独厮守ぢ 2020-12-28 11:53

I have a variable of decimal type and I want to check the number of digits before decimal point in it. What should I do? For example, 467.45 should

25条回答
  •  萌比男神i
    2020-12-28 12:07

    In order to get an accurate and culturally agnostic answer I do the following:

    1. Use System.Numerics.BigInteger, whose constructor accepts a decimal and doesn't seem to produce any rounding errors.
    2. Use BigInteger.Abs() to remove any sign.
    3. Use BigInteger.ToString() with the "#" format to suppress any separators that might occur.

    Code

    decimal num = 123213123.123123M;
    int length = BigInteger.Abs((BigInteger)num).ToString("#").Length;
    

提交回复
热议问题