Friday, January 15, 2010

Rounding in Ruby String Format

Ruby has a nice sting format operator, % for formating in a sprintf-like fashion:
$ irb
irb(main):001:0> "%2.1f" % 12.8987987
=> "12.9"
Works well, but the rounding can be correct:
irb(main):002:0> "%2.1f" % 2.85
=> "2.9"
or incorrect:
irb(main):003:0> "%2.1f" % 12.85
=> "12.8"
To compensate, use round and some decimal-place finangling:
irb(main):004:0> "%2.1f" % ((12.85*10.0).round/10.0)
=> "12.9"

1 comment:

Anonymous said...
This comment has been removed by a blog administrator.