I want to trim my decimal into something like 8.063 instead of the original which is 8.0638304611694E-9. I have implemented a function for it but it doesn't work when there is E-9 in it. Which part should I modify??
public function setPrecision($number, $decimals = 0)
{
$negation = ($number < 0) ? (-1) : 1;
$coefficient = 10 ** $decimals;
return $negation * floor((string)(abs($number) * $coefficient)) / $coefficient;
}
EDIT
The current implementation gave me 0 when I try to call the function.
setPrecision(8.0638304611694E-9, 3); // 0
In PHP, there are (at the moment of writing) 8519 builtin functions. One of them probably does the trick!
You could use log10() and round() in your function:
function setPrecision($number, $precision = 0)
{
$exponent = floor(log10($number)) - 1;
return round($number, -$exponent + $precision - 1);
}
Relative rounding with a certain number of digits can easily be done with sprintf.
$round = (float)sprintf('%0.3E', 8.0638304611694E-9);
var_dump($round); //float(8.064E-9)
On this basis I have this function which rounds float values with a certain relative decimal precision.
/*
* @return Float-Value with reduced precision
* @param $floatValue: input (float)
* @param $overallPrecision: 1..20 (default 10)
*/
function roundPrecision($floatValue, $overallPrecision = 10)
{
$p = min(20,max(0,$overallPrecision-1));
$f =(float)sprintf('%.'.$p.'e',$floatValue);
return $f;
}
example 1
$float = 0.0000123456789;
$newFloat = roundPrecision($float,5);
printf('%0.10f',$newFloat); //0.0000123460
example 2
$float = 3456.7891234;
$newFloat = roundPrecision($float,5);
printf('%0.10f',$newFloat); //3456.8000000000