0

my function is as follows:

static function applyPrecision($vals) {
        $originalNumber = $vals['reading'];
        if (is_numeric($originalNumber)) {
            $precision = ($vals['precision'] != '' || $vals['precision'] != 0) ? $vals['precision'] : 4;
            $factor = pow(10, $precision);
            $multipliedNumber = $originalNumber * $factor;
            //$integerMultipliedNumber = floor($multipliedNumber);
            $var = explode(".", $multipliedNumber);
            $integerMultipliedNumber = $var[0];
            return $result = (float) ($integerMultipliedNumber / $factor);
        } else {
            return $originalNumber;
        }
    }

using this , we can apply precision for a number without rounding the value for eg:- 45.12345678 precision given is 3,then output is 45.123

but if a number like this, :45.1000000 and precision is 3 then output coming like 45.1 only, that zeros are getting skipped, is there any way to avoid this?

sarin
  • 35
  • 8

2 Answers2

0

If this is a question about floats, 14.1 is the same as 14.100. If this is a question about strings then you should instead just be using substr(). Answer for that below where $number is the number to cut and $precision is how many decimal places you want.

$number = (string) $number;
$temp = $precision <= 0 ? 0 : $precision+1;
return substr($number, 0, strrpos($number, '.') + $temp);
Shardj
  • 1,800
  • 2
  • 17
  • 43
0

In order to get the first 3 subdigits of the float without rounding up you have to use float($number*1000/1000) then you use that with number_format(float($number*1000/1000),3)

example

$var =0.35489;
$var2 = number_format(floor($var * 1000) / 1000,3);
echo $var2;

output

0.354

example2

$var =0.3000;
$var2 = number_format(floor($var * 1000) / 1000,3);
echo $var2;

output2

0.300

If your precision is variable then you will have to use pow(10,$precision)

Example3

$var =0.3000;
$precision =3;
$var2 = number_format(floor($var * pow(10,$precision)) / pow(10,$precision),3);

output3

0.300