如何检查浮点数输入的最大精度为2位数字?

时间:2019-04-27 23:48:16

标签: php

请注意,我不是要舍入浮点数,而是试图建立最大精度来防止舍入错误。例如。

>>> import libmiketest
>>> a = libmiketest.create_obj()
>>> help(a)
Segmentation fault: 11

如果可以使此功能按预期工作,则可能是一个很好的答案:     

1/3 + 1/3 + 1/3 = 1
// when I would round to two decimals that would result in the loss of a cent
0.33 + 0.33 + 0.33 = 0.99
// that is why I want to check a maximum precision on input

注意:使用模数运算符确实让我大吃一惊,但是模数运算符只能用于整数。

注2:我认为对浮点数进行递归删除一次,直到剩下0为止的0.01为止,否则0到0.01之间的值将起作用。但这似乎是解决这一问题的一种优雅而低效的方法。

注3:我可以将浮点转换为字符串,然后使用regExp进行检查,然后将其转换回浮点。但我宁愿检查浮点数本身。

1 个答案:

答案 0 :(得分:0)

使用strlen(substr(strrchr($ a,“。”),1)

function test_input( float $floatingNumber ) {
   if( strlen( substr( strrchr( $floatingNumber, "." ), 1 ) ) )
     echo 'Okay, this number has 2 or less digits';
   else
     echo 'string has too many digits';
}