Convert to integer type of minimum required size

Doing a conversion like this is type-unstable (because it depends on the value, not the type), so you wouldn’t normally want to do it in performance-sensitive code. And if you have performance-insensitive code, you might as well just use BigInt.

That being said, you could certainly do something like this in principle:

function tointeger(x::AbstractFloat)
    for T in (Int8, Int16, Int32, Int64, Int128)
        if typemin(T) ≤ x ≤ typemax(T)
            return T(x)
        end
    end
    return BigInt(x)
end

But as I said, doing type-unstable conversions like this will result in slow code.

Why do you want to do this?

2 Likes