How to Format Number Functions in PHP
The PHP programming language has many built-in functions that allow you to shape the way data is displayed to the user. This is very useful given that PHP is traditionally used in websites, and formatting data correctly is very important for web development. One very useful data formatting function is "number_format," which sets the number of decimal places a number displays, the decimal point symbol, and the thousands-place separator. This function is very simple to use and provides a wealth of number formatting options.
Instructions
-
-
1
Decide how you will run your PHP code. If you have a PHP server, you can execute code using PHP files. If you do not have access to a PHP server, you can use an online PHP interpreter. Enter the code in this tutorial into either a PHP file or the online PHP interpreter.
-
2
Begin your PHP program with the following statement:
<?php
-
-
3
Create a variable and assign it some number. Write the following statement:
$num = 25643499.70123;
-
4
Create a variable that will store a formatted number. Invoke the "number_format" function and pass it four arguments: the variable "$num," the number of decimal places (2), the separator for the decimal place, and the separator for the thousands place. To call the function with these arguments, write the following statement:
$commaFormat = number_format($num, 2, '.', ',');
-
5
Print out the result using the "print" function:
print($commaFormat);
-
6
Conclude your PHP program with the statement below. Your program is now ready to be tested on your PHP server or online PHP interpreter.
?>
-
7
Observe the program output. It will look like this:
25,643,499.70
-
1