Code Logo

Format Numbers with number_format()

Published at25 Jul 2026
PHP Functions Easy 1 views
Like0

Write a PHP function that takes a number and returns it formatted with 2 decimal places and commas as thousands separators using number_format(). For example, 1234.5 becomes "1,234.50".

number_format() is a PHP built-in function that formats a number with grouped thousands. It can take 1, 2, or 4 parameters: the number, decimal places, decimal separator, and thousands separator. With default parameters, it uses comma for thousands and period for decimals.

The number_format() function is the standard way to display currency, large numbers, and statistical data in PHP applications. It handles rounding automatically to the specified decimal places and works with both integer and float inputs.

Time complexity is O(1). The function is implemented in C internally and is highly optimized.

Example Input & Output

Example 1
Input
99.9
Output
"99.90"
Explanation

Small number

Example 2
Input
0
Output
"0.00"
Explanation

Zero formatted

Example 3
Input
1000000
Output
"1,000,000.00"
Explanation

Large number

Example 4
Input
-500
Output
"-500.00"
Explanation

Negative number

Example 5
Input
1234.5
Output
"1,234.50"
Explanation

Format with thousands separator

Algorithm Flow

Recommendation Algorithm Flow for Format Numbers with number_format()

Solution Approach

Format a number with grouped thousands using number_format(). This function adds commas (or specified separator) between groups of three digits. It can also control decimal precision and the decimal point character.

function solution($n) {
    return number_format($n);
}

number_format() without additional arguments uses commas for thousands and no decimal places. For decimal formatting: number_format($n, 2) shows two decimal places.

Time complexity is O(1), space complexity is O(1).

Best Answers

php - Approach 1
<?php
function solution($num) {
    return number_format($num, 2);
}