Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate a floating point number without rounding up

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?

like image 748
ab217 Avatar asked Nov 12 '11 18:11

ab217


People also ask

How do I truncate without rounding?

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.

Do you round when you truncate?

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.

What is the difference between rounding and truncating a floating point number?

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.

How do I truncate decimal places?

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.


2 Answers

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

1.237.to_d.truncate(2).to_f # will return 1.23 
like image 89
Sid Krishnan Avatar answered Sep 22 '22 08:09

Sid Krishnan


Assuming you have a float, try this:

(x * 1000).floor / 1000.0 

Result:

1.015 

See it working online: ideone

like image 32
Mark Byers Avatar answered Sep 23 '22 08:09

Mark Byers