# Truncating Floats into a specific Int size

**URL:** <https://discourse.julialang.org/t/truncating-floats-into-a-specific-int-size/55207>\
**Category:** Numerics\
**Created:** [February 13, 2021, 12:28pm UTC](https://discourse.julialang.org/t/truncating-floats-into-a-specific-int-size/55207 "2021-02-13T12:28:26Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Libbum](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/libbum/32/3935_2.png) [@Libbum](https://discourse.julialang.org/u/Libbum)\
**Post date:** [February 13, 2021, 12:28pm UTC](https://discourse.julialang.org/t/truncating-floats-into-a-specific-int-size/55207/1 "2021-02-13T12:28:26Z")

</div>

Hi all.

```julia
julia> floor(Int, convert(Float64, typemax(Int)))
ERROR: InexactError: trunc(Int64, 9.223372036854776e18)

```

I understand _why_ this happens. What I’m looking for here is a nice way of truncating the pathological case of `Float64` values around the size of `typemax(Int)` into an `Int`.

I’m on a 64 bit machine, so my ints are `Int64`. I can do something like this:

```julia
testfloat = convert(Float64, typemax(Int))
convert(Int, min(floor(Int128, testfloat), typemax(Int)))

```

but that seems a little mad. Essentially allowing the `floor` to cast into the `Int128` a value that is `typemax(Int64)+1`, then disallowing that result to be used on the `convert` call.

I essentially have a float that I wish to clamp between `type{min,max}(Int)`, but can’t see a better solution than invoking the larger `Int128` type. Is there a better way to do this? Is there a way to treat the `Int32` case better if not?

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [February 13, 2021, 1:35pm UTC](https://discourse.julialang.org/t/truncating-floats-into-a-specific-int-size/55207/2 "2021-02-13T13:35:30Z")

</div>

Maybe:

```julia
const maxfloatint = setrounding(BigFloat, RoundDown) do; convert(Float64, BigFloat(typemax(Int))); end
floorclamp(x::Float64) = x > maxfloatint ? typemax(Int) : floor(Int, x)

```

---

<div class="post-metadata">

**Author:** ![Libbum](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/libbum/32/3935_2.png) [@Libbum](https://discourse.julialang.org/u/Libbum)\
**Post date:** [February 13, 2021, 2:24pm UTC](https://discourse.julialang.org/t/truncating-floats-into-a-specific-int-size/55207/3 "2021-02-13T14:24:43Z")

</div>

Thanks Steve, certainly looks a lot nicer and passes my tests!
