views:

56

answers:

3

Hi all,

I'm trying to print out a float number, that has the value 5

What I get when it print it out is 5.0, so my question is:

How to i make it so, that if the value is just 5, it will just print 5 without the .0 after it, and if it is 5.2 or so, it will print out that?

I've looked around, but all I found was to either force it one way or another.

Can someone help me in the right direction? Thanks :)

+1  A: 

A couple of dirty solutions.

1.

a = 5.0
puts a.ceil == a ? a.ceil : a

2.

5.1.to_s.chomp ".0" #=> 5.1
5.0.to_s.chomp ".0" #=> 5
floatless
Nice readable solution. I needed to modify it just a little bit for getting it to work:a.ceil == a ? a.ceil.to_i : a
Jesper Blad Jensen aka. Deldy
+2  A: 

Try this:

number.to_s.gsub(/\.?0*$/, '')

This will even work for number = "5.30" # => '5.3'.

Konstantin Haase
Nice, haven't though about using regex for the matter.
Jesper Blad Jensen aka. Deldy
A: 

Why do you want to do this? 5 and 5.000 conveys different messages, because they have different numbers of significant figures. The first indicates "five give or minus a half" whereas the latter indicates "five to the nearest thousandth".

Andrew Grimm
Why should the first indicate "five give or minus a half"? Lack of decimal digits doesn't have to imply rounding of any kind.
Mladen Jablanović
@Mladen: Can you expand further?
Andrew Grimm
the reason is because the user can give a estimate of 5 hours, but also 3.5 hours. To keep the view clean, I don't want to write 5.0 as the .0 is just clutter for the user
Jesper Blad Jensen aka. Deldy
Exactly. Users don't always approach numbers mathematically. In some cases, `5`, `5.0` and `5.000` are equivalents, only of different readability. BTW, why `5` couldn't mean _exactly_ five, and not _five plus or minus half_?
Mladen Jablanović
@Mladen: If it was exactly five, then it'd be an integer, not a float.
Andrew Grimm
... or maybe a fraction.
Andrew Grimm