Ruby Method of the Day - Float.truncate

Posted by Kelly McCauley on Oct 22, 2007

Signature

float.truncate      #=> integer
float.to_i          #=> integer

float.truncate and float.to_i returns the integer portion of float.

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
(1.99).truncate   #=> 1
(1.5).truncate    #=> 1
(1.0).truncate    #=> 1
(0.5).truncate    #=> 0
(-0.5).truncate   #=> 0
(-1.0).truncate   #=> -1
(-1.5).truncate   #=> -1
(-1.99).truncate  #=> -1

(1.99).to_i       #=> 1
(1.5).to_i        #=> 1
(1.0).to_i        #=> 1
(0.5).to_i        #=> 0
(-0.5).to_i       #=> 0
(-1.0).to_i       #=> -1
(-1.5).to_i       #=> -1
(-1.99).to_i      #=> -1

Documentation Reference

Ruby version 1.8.6

www.ruby-doc.org : Float.truncate