PHP Tutorial on Formatting Numbers with Stone River eLearning

We have discussed a lot of basic concepts that are used in PHP in this series of blogs dedicated to help students learn PHP from the scratch. In this blog post, we will be drifting towards an aspect that is less on the technical side and more on the final result in the form of display that you see on your websites. Imagine you visit a website to buy electronics for your home. After scrolling through different items, you come down to three of them to decide upon. Now you check the price tag of each item and suddenly you realize that the mathematics classes that you slept in during school days are coming back to haunt you. The pricing of the products is something similar to this, $32456785. Well we know that it is a very big number for electronic items, but just assume it reaches that point. Do you find the format in which the amount is displayed to be user-friendly? Would you not have liked if it was displayed in the standard format? Even though this might look like a very small issue, however; in the long run, user satisfaction from the smallest of details, determine the success level of the website. As they say, no matter how good your content is, if you do not present it in a good way, you will never get the fruits out of it.

 

How to format numbers in PHP?

Building on our discussion in the previous paragraph, let us discuss how numbers can be actually formatted to be displayed in an organized manner on the browser. PHP has a ‘number_format()’ function that groups the value passed to it in thousands format. The syntax of the ‘number_format()’ function is :

“number_format ( number, decimal, decimal point, separator)”

We will have a closer look at the syntax and the parameters passed to it.

Number: The first parameter is the number value that needs to be formatted. It is mandatory to have the number parameter inside the number_format function and if no other parameter is given, the number is formatted without the decimals and in a comma separated format.

Decimal: The decimal format specifies the number of values that will show up after the decimal point. By default, if the decimal parameter is set, the separation for the decimal value is (.).

Decimal point: This is an optional parameter and specifies the kind of string that needs to be used for decimal points.

Separator: Another optional entity that gives the string to be used for the thousands separator.

 

Note:

  1. Even though the separator parameter is optional, if it is set, it becomes mandatory to set the other three parameters as well.
  2. Generally, we stick with just the first two parameters and the next two are not really required in the standard number format followed across the globe.

Eg:


<?php

$num = 23456.789

echo ‘I have &pound;’, number_format($num,2);

?>

 

GET YOUR FREE PHP EBOOK!

(Visited 718 times, 1 visits today)