php truncate float to 2 decimal places

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:
    printf("%.2f",$v);

    If you want to get float with 2 decimals instead of printing it, you can use the sprintf function.

  • use the number_format function:
    echo number_format($v,2);

    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.

 

If you like my content, please consider buying me a coffee. Buy me a coffeeBuy me a coffee Thank you for your support!
Posted in

Leave a Reply