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?
To get rid of some decimal places without and rounding, use TRUNC(), which is short of truncate. It takes two arguments: the value and the number of decimal places. Whatever is to the right of the specified decimal location is simply discarded. For example, =TRUNC(12.119999, 2) evaluates to 12.11.
When Excel truncates, it chops off part of the entered number and performs no rounding at all. So if you input 345.679 and format the number for no decimal points, it cuts off the digits after the decimal point.
Round computes the nearest number to the input to a specified degree of accuracy. Rounds a value to the nearest integer or to the specified number of fractional digits. Math. Truncate effectively discards the any digits after the decimal point.
To truncate a number to 1 decimal place, miss off all the digits after the first decimal place. To truncate a number to 2 decimal places, miss off all the digits after the second decimal place.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With