[php-src] PR #21273: Fixed GH-12237: sprintf/printf no longer produces negative zero
| From: | lacatoire | Date: | Sat, 21 Feb 2026 22:34:36 +0000 |
| Subject: | [php-src] PR #21273: Fixed GH-12237: sprintf/printf no longer produces negative zero | ||
| Groups: | php.git-pulls | ||
| Request: | Send a blank email to git-pulls+get-34975@lists.php.net to get a copy of this message | ||
Pull Request: https://github.com/php/php-src/pull/21273
Author: lacatoire
## Summary
When a negative floating-point value rounds to zero at the requested precision,
sprintf/printf now outputs "0.00" instead of
"-0.00".
```php
// Before (8.4 and earlier)
sprintf('%.2f', -0.001); // "-0.00"
sprintf('%.0f', -0.1); // "-0"
// After
sprintf('%.2f', -0.001); // "0.00"
sprintf('%.0f', -0.1); // "0"
```
This aligns the behavior of sprintf()/printf() with
number_format(), which already suppresses the negative sign for values that round to
zero.
## Fix
After php_conv_fp() formats the number, if is_negative is set, we check
whether round(fabs(number) * 10^precision) / 10^precision == 0.0. If so, we clear the
negative flag.
The check is only applied to %f/%F formats (for
%e/%E, a non-zero value never formats as zero).
## Test plan
- New test ext/standard/tests/strings/gh12237.phpt covering:
- Basic case from the bug report
- Various precisions (0-4 decimals) where the value rounds to zero
- Values that should remain negative (do NOT round to zero)
- Uppercase %F format
- Explicit + sign flag
- printf() (not just sprintf())
- Consistency with number_format()
- Very small negative values (-1e-10, -PHP_FLOAT_EPSILON,
-1e-100)
- Padding and width specifiers
- Updated sprintf_variation9.phpt for the new expected output
- All 57 existing sprintf/printf/number_format tests pass