Skip to main content
Ruby

RUBY – Working with Integers and Floats

By October 15, 2013September 12th, 2022No Comments



When we work with RUBY then any arithmetic calculation with two integers will only produce an integer ( whole number ). If we want more accuracy then we must use at least one float in the calculation

7 /4 = 1
7.0 / 4 = 1.75
7 / 4.to_f = 1.75

Both the 2nd and 3rd example use floats and we then get an accurate result to the division.

While we talk of decimal places the PI constant can be access as

Math::PI

If we want to format it to just two decimal places then we can use sprintf:

sprintf "%.2f",Math::PI
 3.14

When entering numbers into your Ruby scrip[ts also be careful not to include leading 0’s that are not required

  • A number that start 0 denotes an octal : 0377 = 255
  • A number that start 0b denotes binary: 0b11111111 = 255
  • A number that starts 0x denotes HEX: 0xFF = 255