1

I use the floatval() function to remove useless 0s, but I want to keep at least 3 significant numbers. Like if I have 0.1800000 I want to show 0.180 and if I have 1.8454214 I want to show 1.845421. How can I do a round after 6 digits and remove useless 0s after 3 digits?

$value = 1.80000;
$value = floatval(round($value,6));
echo $value;   //I get 1.8

Or if I have

$value = 1.84542146543;
$value = floatval(round($value,6));
echo $value;   //I get 1.845421

And this works fine, but not if I've got a lot of 0s.

I always need minimum 3 decimal, but it can be more.

Samybel
  • 13
  • 4
  • Per this answer (http://stackoverflow.com/questions/14531679/remove-useless-zero-digits-from-decimals-in-php) you can do `$value + 0` to remove any unnecessary trailing 0s. – WillardSolutions May 16 '16 at 13:54

2 Answers2

1

Try with the below code

$value = 1.80000;
$value = floatval(round($value,6));
$valArr = explode('.', $value);
if(isset($valArr[1])){
    if(strlen($valArr[1]) < 3){
        $valArr[1] = str_pad($valArr[1], 3, "0", STR_PAD_RIGHT);
        $value = $valArr[0].'.'.$valArr[1];
    }
    else{
        $value = floatval(round($value,6));
    }
}

echo $value;

It will work if you want to print the 0s in your web page.

Arun
  • 3,640
  • 7
  • 44
  • 87
0

Use a combination of floor and sprintf to truncate the float to a string with 3 decimal places. Then use max to compare it with the rounded float. PHP will compare the values numerically, returning the first parameter (padded with zeros) if they are numerically the same, only returning the second value if it is numerically greater (ie there is a digit larger than 0 after the third decimal place).

$value = max(
    sprintf("%.3f", floor($value * pow(10, 3)) / pow(10, 3)),
    round($value, 6));
Matt Raines
  • 4,149
  • 8
  • 31
  • 34