Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

วิธีแปลงจำนวนเงินเป็น float และปัดเศษให้ถูกต้องใน PHP

สำหรับการปัดเศษจำนวนเงิน ให้ใช้ฟังก์ชัน round() ใน PHP สมมติว่ามีค่าอินพุตดังนี้

$amount = 50.78; $quantity = 45.5;

แปลงเป็น float และปัดเศษ 4 ตำแหน่งทศนิยม

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

ตัวอย่างโค้ด

โค้ด PHP ดังต่อไปนี้

<!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>

ผลลัพธ์

จะได้ผลลัพธ์ดังนี้

50.78 45.5 The result is=2310.49