Skip to Content
Course content

108: BC Math for Arbitrary Precision

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Why can't I just use standard operators for financial calculations?

You've probably noticed that PHP's floats are convenient, but they're dangerous when precision is non-negotiable. This is because computers represent floats in binary, and some decimal fractions—like 0.1 or 0.7—cannot be represented exactly. If you've ever seen a calculation result in 0.30000000000000004 when it should have been exactly 0.3, you've hit a floating-point precision error.

In a hobby project, that's a nuisance. In a banking app or a crypto exchange, that's a critical bug. That's where BC Math comes in. It treats numbers as strings and performs arithmetic on them manually, much like you did in primary school, ensuring that 0.1 + 0.2 is exactly 0.3.

How do I actually perform basic math with BC Math?

Since BC Math works with strings, you stop using symbols like +, -, and *. Instead, you use functions. I'll show you a quick example calculating a total for a high-value order with a specific tax rate.

// Imagine we are dealing with a very precise tax rate and a large order amount
$subtotal = '1250.45';
$taxRate = '0.0825'; // 8.25%

// Calculate tax: $subtotal * $taxRate
$taxAmount = bcmul($subtotal, $taxRate, 4); 
// Result: "103.1621"

// Calculate total: $subtotal + $taxAmount
$total = bcadd($subtotal, $taxAmount, 2); 
// Result: "1353.61"

Notice how I wrapped the numbers in quotes? That's the key. If you pass a float into these functions, PHP will cast it to a string, but you've already lost the precision by creating the float in the first place. Always keep your precise numbers as strings from the moment they enter your system.

What is this "scale" parameter, and why does it matter?

Almost every BC Math function takes a third argument called $scale. This tells PHP how many digits after the decimal point it should keep. If you omit it, it defaults to 0, which is a common trap for beginners. If you try to multiply 1.5 by 1.5 without a scale, BC Math will give you "2" instead of "2.25".

I usually recommend setting your scale slightly higher than what you actually need for the final display. If you're calculating currency, you might use a scale of 4 or 8 during the intermediate steps to prevent rounding errors from compounding, and then use bcdiv or a rounding function only at the very end when presenting the data to the user.

How do I compare two BC numbers?

You might be tempted to use == or <, but since these are strings, you can run into weird issues—especially if one string has trailing zeros (like "1.50" vs "1.5"). The reliable way is to use bccomp().

bccomp returns 0 if the numbers are equal, 1 if the first is larger, and -1 if the second is larger. It looks like this:

$balance = '100.00';
$cost = '100.0000';

if (bccomp($balance, $cost, 4) === 0) {
    echo "You have exactly enough funds.";
} else {
    echo "Insufficient funds.";
}

I've found that using bccomp makes the intent of the code much clearer to other engineers: you're telling them, "I am intentionally comparing these for arbitrary precision."




📋 Practical Task

Exercise: High-Precision Crypto Transaction Fee Calculator

You are building a module for a cryptocurrency wallet. The user wants to send a specific amount of a token, but your system needs to subtract a transaction fee and then verify if the remaining balance is sufficient.

Requirements:

  • Create a variable $walletBalance with the value "1.23456789".
  • Create a variable $sendAmount with the value "0.50000000".
  • Create a variable $feeRate with the value "0.00125" (representing a 0.125% fee).
  • Calculate the $feeAmount by multiplying $sendAmount and $feeRate. Use a scale of 8.
  • Calculate the $totalDeduction by adding the $sendAmount and the $feeAmount. Use a scale of 8.
  • Use bccomp to check if the $walletBalance is greater than or equal to the $totalDeduction.
  • Print "Transaction Approved" if the balance is sufficient, and "Insufficient Funds" if it is not.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.