Reputation: 10135
I want to display numbers up to 6 decimal points.
Like this:
99.0000001 -> 99
99.000001 -> 99.000001
99.00001 -> 99.00001
99.0001 -> 99.0001
99.001 -> 99.001
99.01 -> 99.01
99.10 -> 99.10
99.00 -> 99
What would be an elegant way to do this in PHP?
Upvotes: -2
Views: 1562
Reputation: 1
// Array of values to divide
$numerators = [1, 1, 1];
$denominators = [2, 3, 6];
// Loop through and calculate the result
foreach ($numerators as $key => $numerator) {
$denominator = $denominators[$key];
$result = $numerator / $denominator;
// Print the result with 6 decimal places
printf("%0.6f\n", $result);
}
Expected Output:
0.500000
0.333333
0.166667
You can use "%0.6f\n
to achieve this
Upvotes: 0
Reputation: 46620
Use round(), with precision 6
<?php
echo round(99.0000001, 6).PHP_EOL;
echo round(99.000001, 6).PHP_EOL;
echo round(99.00001, 6).PHP_EOL;
echo round(99.0001, 6).PHP_EOL;
echo round(99.001, 6).PHP_EOL;
echo round(99.01, 6).PHP_EOL;
echo round(99.10, 6).PHP_EOL;
echo round(99.00, 6).PHP_EOL;
Result:
99
99.000001
99.00001
99.0001
99.001
99.01
99.1
99
Upvotes: 2
Reputation: 36
You can use this. Removal of addition digits after 6th decimal digit.
$z = 99.0000011;
$y = floor($z * 1000000) / 1000000;
Then to calculate amount of digits after decimal remaining.
$str = "$y";
$dcount = strlen(substr(strrchr($str, "."), 1));
Now we have to determine if the value should have decimals or not and if so , need to have 2 or more decimals.
$a = 0;
If ($dcount == 1) {$a = $dcount+1;}
else {$a = $dcount;}
$x = number_format((float)$y, $a, '.', '');
$x would be the required result you are looking for.
Upvotes: 1