How to make number_format() not to round numbers up
PHP's number_format() function is a convenient utility for formatting output, but it adheres strictly to standard rounding rules. When you pass 21.188624 into the function with two decimal places, it rounds the third digit (8) up, resulting in 21,19. If your application logic requires truncation instead of roundingâperhaps to display currency balances that must never exceed a certain threshold or to align with specific accounting standardsâyou need to intervene before passing the value to the formatter.
The core issue lies in how floating-point arithmetic works in PHP and how number_format processes those values. The function does not truncate; it rounds based on the nearest neighbor. To force the display of 21,18, you must artificially lower the number so that standard rounding logic yields your desired result, or explicitly truncate the string representation after formatting.
Mathematical Truncation via Subtraction
The most robust approach without altering the underlying data type involves a simple mathematical offset before formatting. Since number_format rounds to the nearest value at the specified precision, you can subtract half of that precision unit from your number. This ensures that any remaining fractional part below 0.5 will round down to zero effectively, while numbers closer to the upper threshold will still round correctly if they were already intended to be rounded up by standard rules.
For two decimal places, you are working with a step size of 0.01. Half of that is 0.005. By subtracting this value from your original number, you shift the rounding boundary:
$double = '21.188624';
$formatted = number_format($double - 0.005, 2, ',', ' ');
echo $formatted; // Outputs: 21,18
This technique works because 21.188624 is less than 21.195. When you subtract 0.005, the value becomes roughly 21.183624. When number_format evaluates this new value, it sees that the digit in the third decimal place (3) is less than 5, so it rounds down to 21.18.
However, be cautious with negative numbers or edge cases where the subtraction might push the value below a lower threshold unexpectedly if your logic relies on strict equality. This method assumes you want to truncate towards zero for all values in that range.
String Manipulation Approach
If mathematical adjustments feel hacky or if you are dealing with very large numbers where floating-point precision loss becomes a significant concern, manipulating the string output directly is an alternative. You can use number_format to generate the rounded string, then locate the decimal point and truncate the result.
$double = '21.188624';
$formatted = number_format($double, 2, ',', ' '); // "21,19"
// Split by comma (decimal separator)
$parts = explode(',', $formatted);
// Keep only the first two parts if they exist
if (count($parts) === 2) {
$result = $parts[0] . ',' . substr($parts[1], 0, 2);
} else {
$result = $formatted; // Fallback for integers or single part
}
echo $result; // Outputs: 21,18
This method guarantees truncation regardless of the input magnitude. It relies on substr to cut off anything after the second decimal digit. While this is straightforward, it requires handling the locale separators (comma and dot) correctly if your application uses different formatting rules for different regions. If the separator changes from a comma to a dot, the logic must adapt accordingly.
Why round() Might Not Be Enough
A common instinct is to use PHP's built-in round() function with negative precision or specific flags. For instance, one might think round($double, 2) would solve it. However, round() also follows standard rounding rules and will output 21.19 for your input. To get truncation behavior in round(), you must combine it with the subtraction method described earlier:
$result = round($double - 0.005, 2); // 21.18
This reinforces that the root cause is the value passed to the rounding function, not the function itself. Whether you use number_format for display or round for internal calculations, the mechanism to force truncation remains consistent: offset the value before applying the standard rounding algorithm.
Trade-offs and Best Practices
Choosing between mathematical adjustment and string manipulation depends on your specific context. If the number is purely for display purposes in a view layer, string manipulation after formatting is often safer as it prevents any accidental use of the truncated value in subsequent calculations. If you are storing or calculating with the value, ensure that the truncation happens at the exact point where precision loss is acceptable to your business logic.
Always validate the input type. The source material provided a string '21.188624'. While PHP handles numeric strings implicitly in arithmetic operations, relying on implicit casting can sometimes hide bugs. Explicitly casting or ensuring the number is treated as a float before applying these tricks ensures predictable behavior across different PHP versions and environments.
For developers working within the Laravel ecosystem, these patterns are often applied inside controllers or helper methods to ensure clean output before rendering views. If you require more complex financial logic, consider leveraging libraries that handle arbitrary precision arithmetic, though for simple formatting needs, understanding number_format's rounding behavior is sufficient.