How to format numbers in php?

Member

by gilbert , in category: PHP General , 7 months ago

How to format numbers in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , 7 months ago

@gilbert 

In PHP, you can format numbers using the number_format() function. This function takes three parameters: the number you want to format, the number of decimal places you want to display, and the decimal separator and thousands separator.


Here is an example of how to format a number with two decimal places and a comma as the thousands separator:

1
2
3
$number = 1234567.89;
$formatted_number = number_format($number, 2, '.', ',');
echo $formatted_number; // Output: 1,234,567.89


You can also use the setlocale() function to format numbers based on the user's locale. Here is an example:

1
2
3
4
setlocale(LC_MONETARY, 'en_US');
$number = 1234567.89;
$formatted_number = money_format('%i', $number);
echo $formatted_number; // Output: $1,234,567.89


You can explore other formatting options and functions in the PHP documentation: https://www.php.net/manual/en/function.number-format.php