Rounding to a Decimal Place with ruby-units
I am working on a project that involves a number of unit conversions and so I started using ruby-units to facilitate. It is a really flexible library that is really easy to use...I would highly recommend it if you have any need for conversions. I did run into a small issue with it though. I needed to take some value, say 160 kg, and convert it to pounds. That yields the beautiful value of 352.739619 pounds. I need it to be in a %.1f format, and calling .to_s("%.1f") works great if it is a decimal like that. I also needed whole numbers, like 160 kg to show up as "160 kg" and not "160.0 kg". Normally not a big deal. The good ol' brute force multiply-round-divide trick should work, right?
Well, not really, unfortunately. When you divide certain types of Units, it may keep it as a fraction if it doesn't divide evenly. For example...
("160kg".unit.to('lbs') * 10).round / 10 #=> 3527/10 lbsThat isn't what I want, of course. After trying to finagle this one way or another, it finally dawned on me that there is a simple, albeit inefficient, solution to this.
"160kg".unit.to('lbs').to_s("%.1f").unit #=> 352.7 lbsThat's it. Just to_s and then back to a unit. It will round off the zero automatically if it was a ".0".