How to convert 0.5 to 0.50 in php

Is it possible to display "0.5" as "0.50" in php?

I don't mean something like this:

<?php
    $x = 0.5;
    echo($x . "0");
?>

      

So this could fit in as well:

$x = 0.75;

      

I hope my question is accurate enough. Thank you for your help!

+3


source to share


5 answers


Do

$x = 0.5;
printf("%.2f", $x);

      

Receive:

0.50

      

Explanation:

printf()

and sprintf()

can print / return a formatted string. There are many options options . Here I have used %.2f

. Let's take this separately:



  • %

    denotes a placeholder to be replaced with $x

  • .

    denotes a precision specifier
  • 2

    belongs to the precision specifier - the number of digits after the decimal point
  • f

    - type specifier, here float as what we pass

As an alternative:

Use number_format()

:

echo number_format($x, 2);

      

Here 2

denotes the number of decimal digits you want in the output. You don't actually need to specify the third and fourth parameters as their default values ​​are exactly what you want.

+5


source


Use the number_format () function



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

      

+2


source


Use number_format

Function

<?php
print number_format('0.5',2,'.','');

// 0.50
?>

      

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

0


source


You need to use number_format

 $x = 0.5;
 echo number_format($x, 2, '.', '');

      

Output = 0.50

0


source


I think using .. Sprintf ("% 02F", $ string); Or number_format ()

0


source







All Articles