agentbanks217 agentbanks217 - 1 month ago 7
Ruby Question

How to truncate a floating point number without rounding up in Ruby?

I have a floating point number that I want to truncate to 3 places but I don't want to round up. How would I go about doing this in Ruby? Any help would be much appreciated?

Ex: 1.0155555555555555 => 1.015 not 1.016

Answer

Assuming you have a float, try this:

(x * 1000).floor / 1000.0

Result:

1.015

See it working online: ideone