Formatting Numbers in PHP

- 1 minute read

We can use PHP’s versatile number_format function to format numbers.

The most basic usage involves adding commas where appropriate:

$string = number_format(12345);

// $string will equal "12,345"

The default notation uses commas to separate thousands, but the separation instructions can be overriden:

$string = number_format(12345.67, 0, ',', ' ');

// $string will equal "12 345,67"

Anyway, you can also use the second parameter to round numbers to a certain decimal place (0 is the default):

$string = number_format(12345.6789, 2);

// $string will equal "12,345.67"

If you just want to round to a certain decimal place without adding commas, you can do so like this:

$string = number_format(12345.6789, 2, '.', '');

// $string will equal "12345.67"

Link to this section Conclusion

Thanks for reading!

Ever since PHP’s money_format() function was deprecated, number_format() provides a great alternative for formatting currency amounts and other numerical values to be more human-readable.