PHP number_format() Tutorial

beginner
5 min

PHP number_format() Tutorial

Welcome to our comprehensive guide on the number_format() function in PHP! This function is a handy tool for formatting numbers in a user-friendly way, making them easier to read and understand. Let's dive in!

Understanding number_format()

πŸ’‘ Pro Tip: The number_format() function is a built-in PHP function that converts numbers to a string with a readable grouping.

php
$number = 1234567; $formattedNumber = number_format($number); echo $formattedNumber; // Output: 1,234,567

In the example above, we've used the number_format() function to convert a large number (1234567) into a more readable format (1,234,567).

Number Formatting Options

The number_format() function allows us to specify formatting options using additional parameters.

php
$number = 1234567.89; $formattedNumber = number_format($number, 2); // Formats the number with 2 decimal places echo $formattedNumber; // Output: 1,234,567.89 $formattedNumber = number_format($number, 2, ',', '.'); // Formats the number with 2 decimal places and custom separators (comma as thousands separator, period as decimal separator) echo $formattedNumber; // Output: 1.234.567,89

In the example above, we've demonstrated two usage scenarios:

  1. Formatting a number with a specific number of decimal places.
  2. Using custom separators for thousands and decimal places.

Advanced number_format() Usage

πŸ“ Note: The number_format() function can also be used to format numbers as currency.

php
$amount = 1234.56; $currency = '$'; $formattedAmount = number_format($amount, 2) . $currency; echo $formattedAmount; // Output: $1,234.56

In the example above, we've created a formatted amount that includes a currency symbol.

Quiz Time!

Quick Quiz
Question 1 of 1

What does the `number_format()` function do in PHP?

By now, you should have a good understanding of the number_format() function in PHP. It's a powerful tool that makes working with large numbers much more manageable and user-friendly. Happy coding! πŸš€