Truncate a floating point number without rounding up
Solution 1
Assuming you have a float
, try this:
(x * 1000).floor / 1000.0
Result:
1.015
See it working online: ideone
Solution 2
You can also convert to a BigDecimal, and call truncate on it.
1.237.to_d.truncate(2).to_f # will return 1.23
Solution 3
Since ruby 2.4 Float#truncate
method takes as an optional argument a number of decimal digits:
1.0155555555555555.truncate(3)
# => 1.015
Solution 4
Multiply by a thousand, floor, divide by a thousand, making sure to do a float division.
(x * 1000).floor / 1000.0
Or, in Ruby 1.9.2, using a version of round that wasn't available in earlier versions,
(x - 0.0005).round(3)
Solution 5
sid's answer is fine but it misses the first requirement and thus fails Anwar's test. the requirement there is we must start raw so that ruby does not convert the number readily. and to start raw as raw gets is to use a plain string, so
> "59.99999999999999999999".to_d.truncate(2) => #BigDecimal:55a38a23cd68,'0.5999E2',18(45)> > "59.99999999999999999999".to_d.truncate(2).to_s => "59.99" > "59.99999999999999999999".to_d.truncate(2).to_f => 59.99
just sharing this now, since i just encountered this problem myself today : )
ab217
Updated on August 09, 2020Comments
-
ab217 over 3 years
I have a floating point number that I want to truncate to 3 places but I don't want to round up.
For example, convert
1.0155555555555555
to1.015
(not1.016
).How would I go about doing this in Ruby?