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

PHP – บวก Arbitrary Precision Numbers ด้วย bcadd()

ฟังก์ชัน bcadd() ใช้บวก arbitrary precision numbers 2 ตัว รับค่าเป็น string คืนค่าผลบวกหลังปัดเศษตาม precision

รูปแบบการใช้งาน (Syntax)

string bcadd(string $num_str1, string $num_str2, int $scaleVal = 0)

พารามิเตอร์

  • $num_str1 – เลขตัวแรก (left operand) string
  • $num_str2 – เลขตัวที่สอง (right operand) string
  • $scaleVal – จำนวนหลักทศนิยมในผลลัพธ์ (optional, default 0)

ค่าที่คืนกลับ

คืนผลบวกของสอง operand เป็น string

ตัวอย่าง 1: ไม่ใช้ scaleVal

<?php
$num_string1 = "5";
$num_string2 = "10.555";
$result = bcadd($num_string1, $num_string2);
echo "Output without scaleVal is: " . $result;
?>

ผลลัพธ์

Output without scaleVal is: 15

คำอธิบาย: ไม่ใช้ $scaleVal ทำให้ทศนิยมหลัง 15 ถูกตัดทิ้ง

ตัวอย่าง 2: ใช้ scaleVal = 2

<?php
$num_string1 = "5";
$num_string2 = "10.555";
$scaleVal = 2;
$result = bcadd($num_string1, $num_string2, $scaleVal);
echo "Output with scaleVal is: " . $result;
?>

ผลลัพธ์

Output with scaleVal is: 15.55