How to convert amount to float and round correctly in PHP?


To round amounts, use round() in PHP. Let’s say the following are our input values −

$amount=50.78;
$quantity=45.5;

Convert them to float like this 

$am=(float) round($amount, 4);
$quant=(float) round($quantity, 4);

Example

The PHP code is as follows

 Live Demo

<!DOCTYPE html>
<html>
<body>
<?php
$amount=50.78;
$quantity=45.5;
$am=(float) round($amount, 4);
echo $am,"<br>";
$quant=(float) round($quantity, 4);
echo $quant,"<br>";
$correctAmount=round($am*$quant,4);
echo "The result is=",$correctAmount;
?>
</body>
</html>

Output

This will produce the following output

50.78
45.5
The result is=2310.49

Updated on: 13-Oct-2020

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements