Yeldho Paul - 1 year ago 49

PHP Question

I have a value in a PHP variable like this:

`$var='2.533333345';`

echo $var;

What I want is to delete all decimal points after 5 digits.

like now the value of the variable will be

`$var='2.53333';`

echo $var

also, if

`$var ='2.500000000';`

`$var = '2.50';`

Answer Source

Here's one way to do it.

First, trim off all the trailing zeroes.

```
$var = rtrim($var, '0');
```

Then, get the string after the decimal.

```
$decimal = explode('.', $var)[1];
```

Depending on how many non-zero digits are after the decimal, apply a different number format.

```
if (strlen($decimal) > 2) {
// display five decimal places for numbers without trailing zeroes
$var = number_format((float) $var, 5, '.', '');
} else {
// display two decimal places for numbers with only zeroes past two places
$var = number_format((float) $var, 2, '.', '');
}
```