PHP-查找十进制数中的零数 [英] PHP - Find the number of zeros in a decimal number

查看:80
本文介绍了PHP-查找十进制数中的零数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有0.00045。我想找到一种方法来计算小数点后的有效零(在这种情况下为3)的数量。我一直在尝试实现 strpos substr ,但是我遇到了麻烦。

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 strpos or substr, but I'm getting stuck.

其他exs ....

Other exs....

3.006405:应返回 2

0.0000062:应返回 5

9.0100000008:应该返回 1

3.006405: Should return "2"
0.0000062: Should return "5"
9.0100000008: Should return "1"

任何想法吗?

推荐答案

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

strspn 查找零序列的长度。 strpos 找到小数点的位置,我们从小数点后的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.

但是,不适用于 0.0000062 ,因为它在转换为字符串时会转换为科学计数法: 6.200000e-6 。当数字以 e-< exponent> 结尾时,零的数量为< exponent> -1 。您可以使用正则表达式进行检查。

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-<exponent>, the number of zeroes is <exponent>-1. You can check for this with a regular expression.

这篇关于PHP-查找十进制数中的零数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆