find the “string length” of an int

前端 未结 6 1863
情话喂你
情话喂你 2020-12-31 21:13

basically I want to return the number of digits in the int -> values like this:

(int)1 => 1
(int)123 => 3
(int)12345678 => 8

I kno

6条回答
  •  别那么骄傲
    2020-12-31 21:52

    use

    int d = (value == 0 ? 1 : (int)(log10(value)+1));
    

    Note that this doesnt work for negative numbers, you'll have to use

    int d = (value == 0 ? 1 : ((int)(log10(fabs(value))+1) + (value < 0 ? 1 : 0)));
    

    which adds 1 for the minus sign, if value is negative.

提交回复
热议问题