PHP number_format function

 The PHP number_format function can be used to format a number, add a comma in the thousandth place, or set the number of decimal places to be reserved, and even set the symbol style to be displayed for the decimal point or thousandth place by yourself, if you need to deal with it For formatting thousands of numbers, the number_format function is a very useful function.


Basic syntax of PHP number_format function
string number_format ($number, $decimals, $dec_point, $thousands_sep)
The number_format function has four parameters that can be set, but not all of them need to be used. The designer can decide to use a single parameter (only the first parameter can be used in this case), two parameters or four parameters ( It is not possible to use only three parameters). Assuming that only the first parameter $number is used, and nothing else is set, the number_format function will automatically format $number into a number format with thousands of commas, assuming the second is added The number_format function will retain the number of digits after the decimal point to the specified value. The first two parameters are numbers. The third parameter $dec_point and the fourth parameter $thousands_sep must be used together, $dec_point Represents the new decimal symbol, and $thousands_sep is the thousandth symbol. The example mentions the results of using these two parameters.

PHP number_format function example
<?php
$test_number = 3456.56;

echo number_format($test_number).'<br>';
echo number_format($test_number,1).'<br>';
echo number_format($test_number, 2,',','. ');
?>
The above example output
3,457
3,456.6
3.456,56
At the beginning of the example, a set of test numbers "$test_number = 3456.56;" is set, and then we use three lines of echo to output the formatting result of the number_format function. The first format only uses the first parameter, so the default The result is that there is no decimal point, and then the thousandth place automatically adds a comma. As can be seen from the first formatting, the default feature of the umber_format function will automatically round the digits after the decimal point during the formatting process. Pay more attention to this point when you use it again. In the second output, a second parameter was added and set to 1, which means that we want to keep 1 decimal place. From the example output, you can see that the umber_format function will also be automatically rounded. The third output uses a total of four For each parameter, replace the thousandth with a dot and the decimal with a comma. Such cases may be seldom used in actual situations and are for reference only.

Post a Comment

0 Comments