Float Type
A Float is a number with a decimal point, like a measured length. It is for things that are not whole, like 3.14.
In this page:
Syntax
number = 3.14
number.round(2)
number.class # Float
Float Type
Float represents floating-point (decimal) numbers in Ruby, following standard IEEE 754 double-precision behavior, including the usual floating-point rounding quirks.
Dividing two integers with / gives integer division, so at least one operand must be a Float to get a fractional result. to_f converts a value to a float explicitly.
Note:
Divide with
10.0 / 3 (or call .to_f on an operand) to force a fractional result instead of integer division.Example: Float Type
price = 19.99
puts price.class
puts price * 2
puts 10 / 3 # integer division
puts 10.0 / 3 # float division
puts 10.to_f / 3
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Comparing floats with
==, as in0.1 + 0.2 == 0.3, which isfalse; compare with a tolerance or useround. - Writing
10 / 3and expecting3.33, when both operands are integers and the result is3. - Using
Floatfor money, when rounding errors can add up andBigDecimalor cents inIntegerare safer.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: