Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert 0.5 to 0.50 in php [duplicate]

Tags:

php

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!

like image 639
StarCrate Avatar asked Oct 27 '25 05:10

StarCrate


1 Answers

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.

like image 97
domsson Avatar answered Oct 29 '25 20:10

domsson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!