Get number of digits before decimal point

前端 未结 25 2007
独厮守ぢ
独厮守ぢ 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条回答
  •  太阳男子
    2020-12-28 12:03

    I haven't tested this but I would keep it straightforward and do:

    decimal value = 467.45;
    string str = Convert.toString(value); // convert your decimal type to a string
    string[] splitStr = str.split('.'); // split it into an array (use comma separator assuming you know your cultural context)
    Console.WriteLine(splitStr[0].Count); // get the first element. You can also get the number of figures after the point by indexing the next value in the array.
    

    This does not handle negative numbers. If you care about those then considering taking the absolute value. Furthermore, if you want 0 before the decimal place to not be counted then you can use a simple if statement to check it.

提交回复
热议问题