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.

 

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:
Posted in

Leave a Reply