Yeldho Paul Yeldho Paul - 1 year ago 69
PHP Question

Fix decimal places up to 5 and remove zeroes after 2 decimal places

I have a value in a PHP variable like this:

echo $var;

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

like now the value of the variable will be

echo $var

also, if
$var ='2.500000000';
, I need only
$var = '2.50';
. I need to remove zeros after 2 decimal places.

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, '.', '');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download