Forum: Ruby on Rails Remove trailing zeros

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
068d5aec7da6333ce34a848ed4867668?d=identicon&s=25 northband (Guest)
on 2009-02-27 07:21
(Received via mailing list)
Hi -

I am working with floats and am wondering how I can trim the decimal
and trailing zeros on my whole numbers.  For instance, whole numbers
are being displayed as 1.0, 2.0, 3.0, etc...  I would like to remove
the decimal and any trailing zeros with out effecting other non-whole
number floats (ex. 1.375).

Any ideas?  Help appreciated.
10f7e00c1c5c60e2173995eb16f4ffc7?d=identicon&s=25 pepe (Guest)
on 2009-02-27 21:13
(Received via mailing list)
Maybe you can convert them to integers?

my_float = 2.0
my_float = my_float.to_i if my_float == my_float.to_i

068d5aec7da6333ce34a848ed4867668?d=identicon&s=25 northband_101 (Guest)
on 2009-02-27 21:30
(Received via mailing list)
Thanks - this seems easy enough.
6883e5ef03484d4fcef507d7b4f1d243?d=identicon&s=25 Matt Jones (Guest)
on 2009-02-27 21:34
(Received via mailing list)
The %g specifier to sprintf will do this automatically:

"%g" % 1.0
=> "1"

"%g" % 1.375
=> "1.375"

--Matt Jones
068d5aec7da6333ce34a848ed4867668?d=identicon&s=25 northband_101 (Guest)
on 2009-03-12 15:16
(Received via mailing list)
Thanks Matt - I'll try this out.

0fc60326968a0eaccf30330fe6758375?d=identicon&s=25 Juan Kinunt (kinunt)
on 2010-04-20 11:46
And how can I remove the trailing zeros if the value is to be shown in a
text field?


<%= linea_form.text_field :unidades, :id => "invoice_line_units", :name
=> "invoice[lines_attributes][#{id_or_index}][units]", :size => 10 %>

Matt Jones wrote:
> The %g specifier to sprintf will do this automatically:
> "%g" % 1.0
> => "1"
> "%g" % 1.375
> => "1.375"
> --Matt Jones
This topic is locked and can not be replied to.