PHP Number Formatting Techniques

PHP Number Formatting Techniques

If you are working in PHP and dealing with big numbers and make it more readable to your user then “number_format()” is a great PHP function that can accomplish your number formatting task. This function takes number as input and number may be in integer or floating point values. By default number_format function add comma(,) between group of thousands. But you can use custom symbol in number_format function. Example 2 will show you a technique how to use custom symbol.

An important thing is that, when you change number structure using “number_format” function then it’s converted numbers in to a String. So, You should manipulate all mathematical calculations before use number_format function.

Example: 01

// define number

$amount = 1257459.7398;

// format number with commas and 2 decimal places

// result: "1,257,459.74"

$new_number = number_format($amount, 2);

echo $new_number;

Example:  02

// define number

$amount = 1957559.7398;

// format number with custom separator

// result: "1'957'559,74"

$new_number = number_format($amount, 2, ',', '\'');

echo $new_number;

Enjoy!

Was this information useful? What other tips would you like to read about in the future? Share your comments, feedback and experiences with us by commenting below!

Leave a Comment

Back To Top