Skip to content Skip to sidebar Skip to footer

In PHP, How To Print A Number With 2 Decimals, But Only If There Are Decimals Already?

I have a basic index.php page with some variables that I want to print in several places - here are the variables:

Solution 1:

This is simple and it will also let you tweak the format to taste:

$var = sprintf($var == intval($var) ? "%d" : "%.2f", $var);

It will format the variable as an integer (%d) if it has no decimals, and with exactly two decimal digits (%.2f) if it has a decimal part.

See it in action.

Update: As Archimedix points out, this will result in displaying 3.00 if the input value is in the range (2.995, 3.005). Here's an improved check that fixes this:

$var = sprintf(round($var, 2) == intval($var) ? "%d" : "%.2f", $var);

Solution 2:

<?php

$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands seperator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>

more info here http://php.net/manual/en/function.number-format.php


Solution 3:

You could use

   if (is_float($var)) 
   {
     echo number_format($var,2,'.','');
   }
   else
   {
     echo $var;
   }

Solution 4:

What about something like this :

$value = 15.2; // The value you want to print

$has_decimal = $value != intval($value);
if ($has_decimal) {
    echo number_format($value, 2);
}
else {
    echo $value;
}


Notes :

  • You can use number_format() to format value to two decimals
  • And if the value is an integer, just display it.

Solution 5:

you can use number_format():

echo number_format($firstprice, 2, ',', '.');

Post a Comment for "In PHP, How To Print A Number With 2 Decimals, But Only If There Are Decimals Already?"