How to round decimals in PHP to match Google's results

294 views Asked by At

I am trying to develop a php code to match decimals in the same exact way which Google calculator returns results, the math being used is 3.14159265 (pi) * three digits, for example in php pi * 123 returns 386.41589595, however Google returns 386.415896. I have tried the ceil, round, and other functions to no avail. I need the exact methodology Google math uses to round/reduce its numbers for pi * digits

This is because an application this will be used for only returns accurate results using pi * digit results modelled in Google calculator's fashion, any help would be appreciated. Here are some other examples, I have tried to figure out what math is being used to round but I have been unfortunate so far.

pi * 205 = 644.026494 (Google results, which I want/need, scraping Google will not suffice, I need to develop a native php method of obtaining this exact result, where "205" is will usually be a random number three digit number, just using as example in this case)

in php 205*pi = 644.02649325, I need the numbers after the periods to match exactly the results Google's calculator returns.

How could I go about implementing this? Basically I need the exact results google would return for pi * digit (three digit number), without having to depend on Google (scraping the results). There must be some way to do this in php but the my experimentation has been fruitless thus far. I am not the best math student. I would appreciate some help, Richard. Thank you.

4

There are 4 answers

0
Derik Nel On
round(pi() * 123,6) gives 386.415896
0
djot On
<?php
$test =pi() * 123;
echo $test.'<br />';
$test1 = round($test, 6, PHP_ROUND_HALF_UP);
$test2 = round($test, 6, PHP_ROUND_HALF_DOWN);
echo $test1.'<br />';
echo $test2.'<br />';

386.41589639154 < Can't really become 5 at the end
386.415896
386.415896
?>
0
Michal On

Check your precision / approximation settings. This should work for you

echo round(205*M_PI,6); 
0
maxjackie On

use this

echo bcmul('3.14159265', '123', 8),"\n";

this bcmul function will take third parameter as precision

refer this