liveBook · Manning

Floating-point arithmetic

As explained in The Well-Grounded Rubyist, Fourth Edition

Float is Ruby's built-in class for representing finite-precision floating-point numeric values.

Floating-point arithmetic represents numeric values through Ruby’s built-in Float class. Floats are scalar objects, and Ruby lets them respond to messages such as round. section 8.0 section 8.3

Use floating-point values when arithmetic should produce a non-integer result:

  • Integer division remains integer division: 16 / 5 produces 3. section 8.3.2
  • Including a Float produces floating-point division: 10 / 3.3 produces 3.0303030303. section 8.3.2
  • Floating-point operands also support ordinary addition, such as 1.2 + 3.4 producing 4.6. section 8.3.2

Convert values with to_f when permissive string handling is appropriate: "1.23hello".to_f returns 1.23 and "hello".to_f returns 0.0. Float performs stricter conversion and raises an exception for invalid input. section 7.4.3

Temperature conversion

A Celsius-to-Fahrenheit calculation uses multiplication, division, and addition: fahrenheit = (celsius * 9 / 5) + 32. Using floating-point values makes the converter suitable for real-world fractional temperatures. section 1.1.5

Table 8.1 Common arithmetic expressions and their evaluative results

Expression

Result

Comments

1 + 1

2

Addition

10/5

2

Integer division

16/5

3

Integer division (no automatic floating-point conversion)

10/3.3

3.0303030303

Floating-point division

1.2 + 3.4

4.6

Floating-point addition

-12 - -7

–5

Subtraction

10 % 3

1

Modulo (remainder)

Compare integer and floating-point arithmetic in a compact table of Ruby expressions and results. section 8.3.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains Float as an object, demonstrates arithmetic and rounding, and covers permissive versus strict conversion without detailing representation internals.
Examples
Demonstrates fractional arithmetic, rounding 99.6, string conversion, and Celsius-to-Fahrenheit temperature conversion.
What you can do after
Apply it via Ruby expressions that preserve fractional results, convert input, round values, and calculate temperatures.
How it connects
Connects floating-point arithmetic with Ruby objects, Numeric, Integer, strings, conversion methods, and arithmetic operators.

Also explained in

Compare how 20 books explain floating-point arithmetic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.