Truncating Floats in PHP: Why floor() and bcmath Matter
When you need to strip decimal places from a number without rounding, the instinctive reaction is often to cast it to an integer or use a simple arithmetic operation. If your goal is to turn 1.505 into 1.50, simply casting to (int) or using (float)(...) will truncate the value entirely to 1, discarding the precision you likely intended to keep. The challenge lies specifically in preserving the scale of the number while removing only the unwanted digits at the end.
The most straightforward approach for this specific requirement is utilizing PHP's built-in floor() function, but it requires a slight adjustment depending on how many decimal places you wish to retain. The floor() function always rounds down toward negative infinity. To truncate a float to $N$ decimal places, you can multiply the number by $10^N$, apply floor(), and then divide by $10^N$.
Consider the following logic:
function truncate(float $number, int $decimals): float {
$multiplier = pow(10, $decimals);
return floor($number * $multiplier) / $multiplier;
}
$value = 1.505;
$result = truncate($value, 2); // Returns 1.5 instead of 1.50 (floating point representation)
While this works for basic cases, you must be acutely aware of floating-point arithmetic quirks inherent to the IEEE 754 standard. In PHP, 1.50 might internally be represented as 1.499999999... or 1.500000001.... When you perform calculations involving decimals, these representation errors can compound, leading to unexpected results if not handled carefully. For instance, relying on equality checks with truncated floats can fail because the binary approximation rarely matches the decimal expectation exactly.
For applications where financial precision or strict decimal handling is required, switching to arbitrary-precision arithmetic libraries is often the safer architectural decision. PHP's bcmath extension provides functions that operate on strings representing numbers rather than native floats, effectively avoiding the binary representation pitfalls of standard math functions.
Using bcmod, bcpow, and bcadd allows you to construct a truncation function that behaves deterministically:
function truncateBc(float $number, int $decimals): string {
// Multiply number by 10^decimals using arbitrary precision
$multiplier = bcpow('10', (string)$decimals);
// Truncate the decimal part. bcmod returns the remainder,
// but we need to remove digits beyond the scale.
// A cleaner approach with bcmath is often scaling and casting carefully.
// However, for pure truncation without rounding, string manipulation
// or specific bcmath logic is often preferred over float math entirely.
$scaled = bcmul((string)$number, $multiplier, 0);
$truncated = floor((float)$scaled) / (float)$multiplier;
return $truncated;
}
Actually, a more robust pattern with bcmath avoids converting back to float until the very end, or better yet, keeps everything in string format if the output must remain precise:
function truncateBcSafe(float $number, int $decimals): string {
$multiplier = bcpow('10', (string)$decimals);
$scaled = bcmul((string)$number, $multiplier, 0); // Returns "150" for 1.50 * 100
// We want to floor the scaled value, then divide back.
// Since bcpow returns a string, we need to handle integer division logic carefully.
// A simpler bcmath truncation often involves bcmod to remove the tail:
$remainder = bcmul($number, '10', 0); // Just multiplying isn't enough for arbitrary decimals
// The most reliable bcmath way to truncate is:
// floor(number * 10^decimals) / 10^decimals
$multiplierStr = bcpow('10', (string)$decimals, 0);
$scaledVal = bcmul((string)$number, $multiplierStr, 0);
// Since bcmul returns a string, we can't directly apply floor().
// We usually convert to float for the division if precision isn't critical beyond the scale.
return (string)(floor((float)$scaledVal) / (float)$multiplierStr);
}
The trade-off here is performance and complexity. Using bcmath adds overhead compared to native floats, so it should only be employed when you have a genuine requirement for decimal safety, such as in e-commerce checkout flows or ledger systems. For casual calculations where floating-point error margins are acceptable, the floor() multiplier method remains efficient and readable.
Ultimately, understanding why standard casting fails is the first step. Once you accept that you must manipulate the scale explicitly, the solution becomes a matter of choosing between the speed of native types and the safety of arbitrary-precision math libraries. If your application demands absolute fidelity in decimal handling, integrating tools designed for financial calculations or utilizing bcmath directly is the recommended path forward.