Ruby sprintf bug

Hi

I’ve found this possible bug with sprintf in our production code, but it
seems very odd that no one has reported it so I’m doubting myself.

I’ve tested a few versions (CRuby 2.3.1 and 2.1.9) and it was present in
both.

To reproduce in irb:

sprintf(’%1.0f’, 12.5)

Expected result 13 actual 12

In fact if you look at the number sequence 0.5 -> 99.5 you find the even
half will all round down and the odd half round up.

If you do the same in jruby 2.2.1 you get the expected result of 13.

Many thanks

Kieran

Interesting point. I’m not sure whether this is a bug or just
unspecified behaviour: While class Float defines a method ‘round’, the
documentation for sprintf does NOT say that this method is used for
formatting. Interestingly, it does not say anything about rounding.

The reason for the fact that 12.5 is rounded down, but 13.5 is rounded
up, could perhaps be that 0.135 can’t be represented exactly as a
floating point mantissa, while 0.125 can.

I suggest that you open an issue on the Ruby bugtracker, but not as a
bug against the implementation of sprintf, but against the documentation
which does not explain the effect of rounding. You can provide your case
as example.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs