检查数字1在十进制数字中的位置 [英] Check where number 1 is in decimal number

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

问题描述

我有数百个数字,例如:

I am having hundreds of numbers like:

0.00100000
0.01000000
0.01000000
1.00000000
0.00001000
0.00000100

我需要检查数字1的位置这些数字,所以基本上

I need to check where the number 1 is in those number, so basicly

1.00000000 = 1
0.10000000 = 2
0.01000000 = 3

我尝试了 Round()函数,但有时会打印数字像1.E-6或类似的东西,我需要数字1的确切位置。

I tried Round() function, but it sometimes prints numbers like 1.E-6 or something like that, I need exact location of number 1.

非常感谢您的帮助。

推荐答案

我不会过多地依赖于您在答案中发布的方法。改为使用以下函数:

I wouldn't rely too much on the approach you posted in your answer. Use the following function instead:

function index_of_one($dec)
{
  // maximum precision is 15
  $str = str_replace('.','',sprintf('%.15f', $dec));

  $pos = strpos($str, '1');

  if ($pos === false) {
    return -1;
  }

  return ($pos + 1);
}

示例:

$dec1 = 1.00000000;
$dec2 = 0.10000000;
$dec3 = 0.00010000;

echo index_of_one($dec1); // 1
echo index_of_one($dec2); // 2
echo index_of_one($dec3); // 5

访问此链接对其进行测试。

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

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