Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

php - Check where number 1 is in decimal number

I am having hundreds of numbers like:

0.00100000
0.01000000
0.01000000
1.00000000
0.00001000
0.00000100

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

1.00000000 = 1
0.10000000 = 2
0.01000000 = 3

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

Thank you very much for help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

Example:

$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

Visit this link to test it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...