Integer to Floating Point in Ruby

by Melvin Ram

Okay, this is something weird I ran into today. If you do 3/4 in ruby, it will give you back 0. Basically it has to do with the fact that both are integers.

If you want to divide two numbers and get back a decimal number (aka floating point number), you’ll need at least one of them to be a floating point.

How do you turn an integer into a floating point? Use .to_f or * 1.0 or =+ 0.0

Taking the above example, 3/4.to_f => 0.75

Now, if you want to limit how many numbers show up after the decimal point, you’ll need to use the sprintf function. Here are a few examples:

===============

>> sprintf(‘%0.1f’, (3.to_f/8))

=> “0.4″

>> sprintf(‘%0.2f’, (3.to_f/8))

=> “0.38″

>> sprintf(‘%0.3f’, (3.to_f/8))

=> “0.375″

>> sprintf(‘%0.4f’, (3.to_f/8))

=> “0.3750″

===================

Now, if you need to format numbers instead a view, you should check out the number_to & number_with helpers.

Thanks to Jason King for telling me about all this.

{ 1 comment… read it below or add one }

Jason King February 6, 2009 at 2:45 am

You’re welcome :)

Btw, in case you’re wondering why this is, integer division is often desirable for doing things like:

hours = seconds / 3600
minutes = seconds % 3600 / 60
seconds = seconds % 60

Leave a Comment