C programmer knows how to display float 2 decimal places with printf. In php, how to round float to 2 decimal places? It is definitely necessary to echo float with limited decimal places in some cases. For example, a rating value ranging from 0 to 10 would be better shown to human beings with 1 to 2 decimals, rather than the default 13 decimal places. You can use one of the following functions to show float with 2 decimals(or any number of decimals as you want):
- printf float 2 decimal places:
If you want to get float with 2 decimals instead of printing it, you can use the sprintf function.
- use the number_format function:
This function is easier to use because you do not need to memorize the weird format string in printf.
The difference between the two methods is the printf function actually converts the float to a string with specified decimal places while the number_format function rounds the float to another float with given precision.