The sprintf Ruby class provides the ability to specify the number of decimal places to display.
sprintf("%.1f",track.ratings.average('rating'))
In this example I'm getting the average ratings of a track and ensuring that the average is rounded to 1 decimal place.
Comments left...
Thanks, I did a quick google, your entry popped up, its exactly what I needed :)
Christopher Mar at 03 Feb 08 at 06:48
Thank you!
Peter at 15 Mar 08 at 09:23
Nice snippet. Cheers!
Stephan at 22 May 08 at 10:17
Thanks paul, perfect!
Rob Aldred - Digital Marketing at 04 Jul 08 at 04:34
Warning – with some old versions of Ruby there is a bug with sprintf where it takes 0.01 and returns 0.1. If you find things don’t quite look right have a google around.
x = BigDecimal.new(‘2.02’)
x.to_f
Some versions of 1.8.7 will return 2.2!
Francis Fish at 27 Apr 10 at 03:02
Articles Archive →
Got something to say?