Truncate a floating point number without rounding up

agentbanks217 picture agentbanks217 · Nov 12, 2011 · Viewed 20.5k times · Source

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 to 1.015 (not 1.016).

How would I go about doing this in Ruby?

Answer

Sid Krishnan picture Sid Krishnan · Oct 29, 2015

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

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