Slomojamma
Slomojamma

Reputation: 95

Drop the leading zero using number_with_precision

I have an app that tracks a player's baseball stats. I want it to show Batting Average without the leading zero (.333 instead of 0.333). I've been trying number_with_precision with no luck.

Here is the line from my View:

<%= number_with_precision(@player.batting_average, :precision => 3, 
    :significant => true, :strip_insignificant_zeros => true) %>

Here is the code from the Model:

def batting_average
  self.hits / self.at_bats.to_f
end

Based on the number_with_precision Rails 3.1.3 documentation, :strip_insignificant_zeros only applies to zeros after the decimal and :significant doesn't affect the decimals. Am I missing something simple?

Upvotes: 0

Views: 676

Answers (3)

jstim
jstim

Reputation: 2432

There are a ton of ways to do this, but the main thing to recognize is that you are dealing with a float and will need to convert it over to a string to use things like gsub and [].

Here are some ideas:

def to_ba
  self.to_s[1..-1]
end

or with gsub

def to_ba
  self.to_s.gsub(/^0+/, '')
end

or if you want to get crazy (and this is more for fun than anything else):

def to_ba
  self.to_s.reverse.chop.reverse
end

These are all helper methods that could be added on the end of your value like this:

number_with_precision( stuff ).to_ba

or you could just attach any of these methods to the end of your call like this:

number_with_precision( stuff ).to_s[1..-1]

But I would use the helper if you plan to put batting averages all over the place.

Upvotes: 1

Sam 山
Sam 山

Reputation: 42863

http://www.ruby-forum.com/topic/136990

def trim_lead(n)
    self.gsub!(/^#{n}+/,'')
end

Upvotes: 0

user324312
user324312

Reputation:

No. That's the correct behavior. You could write a helper that does it the right way or just add gsub(/^0+/,'').

Upvotes: 1

Related Questions