Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...