How to convert float/decimal to integer on the low end?

Suppose, I had decimals or floats:

a1 = 5.1
a2 = 5.2
a3 = 5.7
a4 = 5.9
a5 = 5.0

How would I get their integer parts? Namely, 5

To truncate floating point numbers you can use Kernel.trunc.

For decimals though, you’ll need to build something on your own from Decimal.round/3 and Decimal.to_integer/1.

Something like this:

decimal
|> Decimal.round(0, :down)
|> Decimal.to_integer()
3 Likes

FYI floor/1 and truncate/1 return different values for negative number - so make sure which behavior you actually want.

If you expect only non-negative number for a func, put guard on the func definition to avoid any surprise later. :slight_smile:

2 Likes

The description “integer part” clearly indicates the use of truncate which is rounding towards zero, while floor where rounding towards negative infinity.

1 Like