Remove trailing zeros


#1

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.


#2

Maybe you can convert them to integers?

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

Pepe


#3

Thanks - this seems easy enough.


#4

Thanks Matt - I’ll try this out.

Best,
NB


#5

And how can I remove the trailing zeros if the value is to be shown in a
text field?

I.e.:

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

Matt J. wrote:

The %g specifier to sprintf will do this automatically:

“%g” % 1.0
=> “1”

“%g” % 1.375
=> “1.375”

–Matt J.


#6

The %g specifier to sprintf will do this automatically:

“%g” % 1.0
=> “1”

“%g” % 1.375
=> “1.375”

–Matt J.