We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.
In Ruby, there are many methods available which help us to modify a float or integer value.
In the previous versions of Ruby,
we could use methods such as
floor
, ceil
and truncate
in following ways.
1
25.54.floor #=> 5
35.54.ceil #=> 6
45.54.truncate #=> 5
5
Providing an argument to these
methods would result
in ArgumentError
exception.
Ruby community decided to come up with an option to add precision argument .
The precision argument, which can be negative, helps us to get result to the required precision to either side of the decimal point.
The default value for the precision argument is 0.
1
2876.543.floor(-2) #=> 800
3876.543.floor(-1) #=> 870
4876.543.floor #=> 876
5876.543.floor(1) #=> 876.5
6876.543.floor(2) #=> 876.54
7
8876.543.ceil(-2) #=> 900
9876.543.ceil(-1) #=> 880
10876.543.ceil #=> 877
11876.543.ceil(1) #=> 876.6
12876.543.ceil(2) #=> 876.55
13
14876.543.truncate(-2) #=> 800
15876.543.truncate(-1) #=> 870
16876.543.truncate #=> 876
17876.543.truncate(1) #=> 876.5
18876.543.truncate(2) #=> 876.54
19
These methods all work the same on Integer as well.
1
25.floor(2) #=> 5.0
35.ceil(2) #=> 5.0
45.truncate(2) #=> 5.0
5