问题
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.
回答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);
}
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.
回答2:
Looks like I found a solution, used strpos()
function which works perfectly!
Basicly:
strpos(0.01000000, 1)
回答3:
I say using regex is suitable when micro-optimization is not top-priority, when it lessens total function calls, and when it provides a direct, desired result.
Considering your case and the sample input, preg_match_all('/[^.](?=[^1]*1)|1.*/',$number)
does everything in one step. It matches each individual non-dot character that is later followed by a 1
OR from 1
to the end of the string.
(Regex Pattern Demo)
preg_match_all()
's return value is the number of matches, so it delivers exactly what you are asking for -- a count.
Effectively, dots are not counted nor are any of the characters after the first 1
. If there is no 1
found, the count is 0
(not -1 as suggested by the other answer).
Here is a demonstration with a battery of tests (Demo):
$numbers=['0.00100000','0.10000000','0.01000000','1.00000000','0.00001000','0.00000100','0.00000000'];
foreach($numbers as $number){
echo "$number = ",preg_match_all('/[^.](?=[^1]*1)|1.*/',$number),"\n";
}
Output:
0.00100000 = 4
0.10000000 = 2
0.01000000 = 3
1.00000000 = 1
0.00001000 = 6
0.00000100 = 7
0.00000000 = 0
来源:https://stackoverflow.com/questions/48054972/check-where-number-1-is-in-decimal-number