gpt4 book ai didi

php - 如何获取十进制数左右两边的位数

转载 作者:可可西里 更新时间:2023-10-31 22:11:46 27 4
gpt4 key购买 nike

我想知道是否有一种好的方法来获取十进制数 PHP 的右侧/左侧的位数。例如:

12345.789 -> 右侧长度为 3/左侧长度为 5

我知道它很容易通过帮助 string 函数和展开数字来实现。我的意思是,是否有一种数学或编程方式可以比字符串操作更好地执行它。

非常感谢您的回答。

更新

到目前为止,左侧的最佳解决方案是:

$left = floor(log10($x))+1;

但右侧仍然不够。还在等……

最佳答案

要获取左侧的数字,您可以这样做:

$left = floor(log10($x))+1;

这使用以 10 为底的对数来获取位数。

右边更难。一个简单的方法看起来像这样,但由于 float ,它经常会失败:

$decimal = $x - floor($x);
$right = 0;
while (floor($decimal) != $decimal) {
$right++;
$decimal *= 10; //will bring in floating point 'noise' over time
}

这将循环乘以 10,直到没有小数点后的数字。这是用 floor($decimal) != $decimal 测试的。

然而,正如 Ali 指出的那样,给它数字 155.11(一个难以用二进制表示的数字)会得到 14 的答案。这是因为数字存储为类似于 155.11000000000001 的 32 位浮点精度我们有。

因此,需要更强大的解决方案。 (上面PoPoFibo的解决方案特别优雅,用PHP很好地继承了float比较函数)。

事实是,我们永远无法区分 155.11 和 155.11000000000001 的输入。我们永远不会知道最初给出的是哪个数字。他们将被表示为相同的。但是,如果我们在确定小数点“完成”之前定义了我们可以在一行中看到的零的数量,那么我们就可以想出一个解决方案:

$x = 155.11; //the number we are testing

$LIMIT = 10; //number of zeroes in a row until we say 'enough'

$right = 0; //number of digits we've checked
$empty = 0; //number of zeroes we've seen in a row

while (floor($x) != $x) {
$right++;

$base = floor($x); //so we can see what the next digit is;
$x *= 10;
$base *= 10;

$digit = floor($x) - $base; //the digit we are dealing with

if ($digit == 0) {
$empty += 1;
if ($empty == $LIMIT) {
$right -= $empty; //don't count all those zeroes
break; // exit the loop, we're done
}
} else {
$zeros = 0;
}
}

如果合理假设连续 10 个零意味着任何其他数字都无关紧要,这应该会找到解决方案。

但是,我仍然更喜欢 PopoFibo 的解决方案,因为没有任何乘法,PHP 的默认比较函数有效地做同样的事情,没有困惑。

关于php - 如何获取十进制数左右两边的位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21688673/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com