3

Is there a possibility to display "0.5" as "0.50" in php?

I don't mean something like that:

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

So this can fit in too:

$x = 0.75;

I hope my question is exact enough. Thanks for your help!

0

5 Answers 5

5

Do:

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

Get:

0.50

Explanation:

printf() and sprintf() can print/return a formatted string. There are plenty of format parameters available. Here, I used %.2f. Let's take that apart:

  • % denotes a placeholder that will be replaced with $x
  • . denotes a precision specifier
  • 2 belongs to the precision specifier - the number of digits after the decimal point
  • f is the type specifier, here float as that's what we're passing in

Alternatively:

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 supply a third and fourth parameter, as their defaults are exactly what you want.

2

Use number_format() function

echo number_format($x,  2, '.', '');
1
  • Ok fixed , not tested
    – meda
    Apr 15, 2017 at 11:59
0

Use number_format Function

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

// 0.50
?>

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

0

You need to use number_format

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

Output = 0.50

0

i think use.. sprintf("%.02f",$string); Or number_format()

Not the answer you're looking for? Browse other questions tagged or ask your own question.