How to format a price
Short answer
number_format() sets the decimals, the decimal point and the thousands separator:
<?php
echo number_format(1234567.5, 2, ',', ' '), ' €';Output:
1 234 567,50 €Without cents
If cents are not needed, pass zero decimals:
<?php
echo number_format(1234567.5, 0, ',', ' '), ' €';Output:
1 234 568 €A price in cents
Money is more reliably stored as a whole number of cents and divided by a hundred only when printing:
<?php
$cents = 129950;
echo number_format($cents / 100, 2, '.', ' ');Output:
1 299.50Functions used in this recipe
- number_format — Formats a number for display: decimals and a thousands separator.
- round — Rounds a number to a given number of digits.
- sprintf — Returns a string built from a format template.