# Convert floating point to integer type?

Currently, the `float` function allows one to go from an `Integer` type to a floating-point type.

``````julia> float(BigInt)
BigFloat
``````

Is there a function to go the other way, that is given `BigFloat` as an argument, it returns `BigInt`, and similarly for other types?

there is `Base.inttype`, but it seems internal and only has definitions for `Float16/32/64`

What properties do you expect from such a mapping? When you go from integers to floats, the expectation is that the float type will have a wider range than the integer, so conversion is possible (at the price of losing precision).

Going in the other direction, this is impractical because floats have such a wide range.

I was mainly thinking of a map from integers to floats (in the context of axes of arrays), so that given a specific `BigFloat` range, I may choose the axis to be a `BigInt` range. I wasn’t thinking of conversion.

For going from float to integer I normally use `round(T, x)`:

``````julia> round(Int64, 3.14159)
3
``````

It throws an error if the `Float64` value is out of range for an `Int64`:

``````julia> round(Int64, 9e23)
ERROR: InexactError: trunc(Int64, 9.0e23)
Stacktrace:
 trunc
@ Base ./float.jl:902 [inlined]
 round(::Type{Int64}, x::Float64)
@ Base ./float.jl:385
 top-level scope
@ REPL:1
``````

It also works with `BigFloat`/`BigInt`:

``````julia> x=round(BigInt, BigFloat(1.33))
1

julia> typeof(x)
BigInt
``````

I have not tested whether an error is thrown if the `BigFloat` value is out of range for `BigInt`, but probably yes.

I think your best option is define your own function for this, as the API in `Base` is mainly for conversion / promotion and their fallbacks.

Use the abstract type `Integer`:

``````julia> Integer(3.0)
3

julia> Integer(3.0) |> typeof
Int64

julia> Integer(big"3.0")
3

julia> Integer(big"3.0") |> typeof
BigInt
``````

Of course, this only works if the floating-point type is integer-valued. If you want an approximate conversion, then you need to specify an approximation explicitly, e.g. via `round`:

``````julia> round(Integer, 3.1) |> typeof
Int64

julia> round(Integer, big"3.1") |> typeof
BigInt
``````
3 Likes