Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 49 / 68

Formatting Numbers (Padding Digits, Decimal Places)

In this lesson you will learn to format numbers with number_format so amounts and sequential file names display neatly. This is for anyone searching for "PHP number_format how to use".

number_format() fixes the number of decimal places and adds thousands separators automatically. str_pad() pads the front of a number with zeros to a fixed width. Raw calculation results have wildly varying widths, so applying this kind of formatting right before display is standard practice.

The sample code produces an amount with two decimal places and a thousands separator using number_format($price, 2), and a zero-padded three-digit sequence number with str_pad($num, 3, "0", STR_PAD_LEFT).

A common stumbling block for beginners is forgetting str_pad()'s fourth argument (STR_PAD_LEFT). Leave it out and the padding goes on the right by default, which is not the zero-padding you wanted.

number_format's thousands separators are exactly what price displays need, which makes it a workhorse in practice - product prices on e-commerce sites, totals on receipts, and much more.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)