Skip to content

Comments

Fixed GH-12237: sprintf/printf no longer produces negative zero#21273

Open
lacatoire wants to merge 2 commits intophp:masterfrom
lacatoire:fix/sprintf-negative-zero
Open

Fixed GH-12237: sprintf/printf no longer produces negative zero#21273
lacatoire wants to merge 2 commits intophp:masterfrom
lacatoire:fix/sprintf-negative-zero

Conversation

@lacatoire
Copy link

@lacatoire lacatoire commented Feb 21, 2026

Summary

When a negative floating-point value rounds to zero at the requested precision, sprintf/printf now outputs "0.00" instead of "-0.00".

// 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).

When a negative floating-point value rounds to zero at the requested
precision, sprintf/printf now outputs "0.00" instead of "-0.00".

This aligns the behavior of sprintf() with number_format(), which
already suppresses the negative sign for values that round to zero.
Co-authored-by: Michael Voříšek <mvorisek@mvorisek.cz>
@alexandre-daubois
Copy link
Member

This looks like a BC break, isn't it? Also, tests are failing

@ndossche
Copy link
Member

This looks like a BC break, isn't it?

If this restores previous behaviour that was unintentionally changed, then it is a regression bugfix.

@alexandre-daubois
Copy link
Member

Ah yes I missed that part, sorry!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants