Topic: adding digits to float

hey all
I would like to know how to have always have two zeros next to the coma so that if I have b=2.0 it displays 2.00 instead, with "b" being a float.

thanx in advance

Pat

Re: adding digits to float

Well, if you don't get any better answers, you can always do

sprintf("%0.2f", b)

BrewControl.com - Brewery and Brewpub management powered by RoR

Re: adding digits to float

you can get fancier and embed this functionality right into float. You could override to_s and then your floats are always output that way no matter what. I'd be hesitant to do that though. Or you could create say to_m (for "to_money", assuming the desire to have two decimal places is currency related). Or whatever you'd want to call it:

class Float
   def to_m
      sprintf("%0.2f", self)
   end
end

The nice thing here is to_m will only ever be called on a float, you no longer have to worry about nils working their way in (instead you'll have Ruby yell at you that NilClass does not have a method called 'to_m' and you can spot your errors quicker)

Re: adding digits to float

If you're displaying a price, you can use number_to_currency instead.

<%= number_to_currency 2.0 %>

Railscasts - Free Ruby on Rails Screencasts

Re: adding digits to float

ok thanx a lot to both

Re: adding digits to float

Aha, there's the answer I was looking for: number_with_precision(number, precision=3)
I thought there was a helper to do that, which wasn't related to currency.

BrewControl.com - Brewery and Brewpub management powered by RoR

Re: adding digits to float

lil off topic...

What is the motivation behind doing this stuff with helpers as opposed to inside the class itself?

Obviously you don't want to add stuff to a class like Float willy nilly. But like for me, my site converts between US and metric units all the time. At first I created a suite of helpers to do the job for me. It was such a pain. So for my revision I decided to embed the unit conversions directly into Numeric.

So now I do stuff like

foo.weight = 33.lbs
...
<%= bar.energy.to_kcals %>
...

where weight and energy are both instances of Numeric (typically Float), and wow, my code is *so* much cleaner and less error prone now.

Rails does this too of course, 3.days.ago and all that good stuff. But sometimes they opt for a helper instead. Is there any cut and dry reasoning on when to choose one over the other?

Re: adding digits to float

The way I see it is: if it's view related, it goes in a helper. Converting a number to a currency is view related, especially since it includes the currency symbol. Converting a value from one unit of measurement to another is not view related, so placing it in the class seems appropriate.

Railscasts - Free Ruby on Rails Screencasts