PHP - Find the number of zeros in a decimal number

后端 未结 3 1318
伪装坚强ぢ
伪装坚强ぢ 2021-01-23 22:48

Let\'s say we have 0.00045. I want to find a way to count the number of \"significant\" zeros after the decimal point (3 in this case). I\'ve been trying to implement st

3条回答
  •  旧时难觅i
    2021-01-23 23:20

    strspn($num, "0", strpos($num, ".")+1)
    

    strspn finds the length of a sequence of zeroes. strpos finds the position of the decimal point, and we start from 1 position past that.

    However, this doesn't work for 0.0000062 because it gets converted to scientific notation when converted to a string: 6.200000e-6. When the number ends with e-, the number of zeroes is -1. You can check for this with a regular expression.

提交回复
热议问题