I've got a problem with rounding using sprintf. I get passed '%0.0f' as the format. sprintf rounds not as expected: 0.5 should be rounded to 1, instead it rounds to 0, which is against the general rounding rule, whereas 1.5, 2.5 etc. is being rounded correctly:
sprintf('%0.0f', 0.5)
=> "0"
sprintf('%0.0f', 1.5)
=> "2"
Why is this so and how can I achieve my expected behaviour?
sprintfperforms banker's rounding, which rounds 0.5 to the nearest even number. This method is often used by statisticians, as it doesn't artificially inflate averages like half-up rounding.The
Float#roundmethod (in Ruby 2.4+) accepts a parameter which can be one of:half: :up(the default)half: :downhalf: :even(banker's rounding)Apparently you are expecting
round's default, so you can just do a.roundto your number before printing.