How to display a number with two decimal places in PHP?
Hello everyone! I just started learning PHP and encountered a problem. I need to display product prices on a website so they always show with two decimal places. For example, if the price is 10, it should be 10.00, if 5.5 — it should be 5.50, and if 3.456 — it should be 3.46.\n\nI tried using round() but it doesn't work the way I need. Here's my code:\n\n```php\n$price1 = 10;\n$price2 = 5.5;\n$price3 = 3.456;\n\necho round($price1, 2); // outputs 10, but need 10.00\necho round($price2, 2); // outputs 5.5, but need 5.50\necho round($price3, 2); // outputs 3.46, this is correct\n```\n\nThe problem is that round() just removes extra digits, but doesn't add zeros if they are missing. I need the number to always be strictly in the format "X.XX", even if it's a whole number.
No answers yet.
Log in to leave an answer
Blogs