Truncate a floating point number without rounding up Truncate a floating point number without rounding up ruby ruby

Truncate a floating point number without rounding up


You can also convert to a BigDecimal, and call truncate on it.

1.237.to_d.truncate(2).to_f # will return 1.23


Assuming you have a float, try this:

(x * 1000).floor / 1000.0

Result:

1.015

See it working online: ideone


Since ruby 2.4 Float#truncate method takes as an optional argument a number of decimal digits:

1.0155555555555555.truncate(3)# => 1.015