Home >Backend Development >PHP Tutorial >How to Format Numeric Values to Two Decimal Places in PHP?
Formatting Numeric Values with Decimal Places
In the provided PHP script, the numbers are not displaying with the desired two decimal places. To address this issue, we can utilize formatting techniques.
The printf function can be employed to specify the desired format for the number. The syntax printf(".2f", $start) formats the value of the variable $start with one digit before the decimal point and two digits after the decimal point.
Alternatively, the number_format function can be used to format the number according to specific formatting rules for different countries. For example, number_format($start, 2) will format $start with two decimal places using the system's default formatting rules.
By utilizing these formatting techniques, the script can be modified to display the desired decimal precision:
<?php $inc = 0.25; $start = 0.25; $stop = 5.00; ?> <?php while($start != ($stop + $inc)){ ?> <option><?php printf("%.2f", $start); ?></option> <?php $start = $start + $inc; ?> <?php } ?>
Now, the script will display the values in the desired format: 5.00, 4.00, 3.00, and 3.50.
The above is the detailed content of How to Format Numeric Values to Two Decimal Places in PHP?. For more information, please follow other related articles on the PHP Chinese website!