Should conversion of BigFloat to Float be called rounding instead?

The conversion of a Float64 to Int is allowed only if it exists an exact representation of that number as Int, otherwise the conversion throws an InexactError. This seems inconsistent with the conversion of a BigFloat to a Float64, see third example, which more than a conversion, it sounds like rounding to me.

julia> convert(Int, 1.0)
1

julia> convert(Int, 0.2)
ERROR: InexactError()
 in convert(::Type{Int64}, ::Float64) at .\int.jl:239

julia> convert(Float64, big"0.21221890538903469203434")
0.21221890538903468
1 Like

Although you make a good point, I believe (but am not sure) that conversions like this are required by the IEEE 754 standard on floating-point arithmetic.

Note that you can indeed use rounding with eg

Float64(x, RoundDown)

I am not sure what it is meant by RoundDown:

julia> Float64(big"0.123456789012345678", RoundUp)
0.12345678901234569

julia> Float64(big"0.123456789012345678", RoundDown)
0.12345678901234568

Unless it is a display issue, the last digit should be 8 and 7 respectively. The docs seem to imply this.

These round to the nearest Float64 in the given direction.

It is partly a display issue. The display of Float64 uses an algorithm called “Grisu”, that displays the smallest number of digits possible. You can use big(x) to see the exact decimal representation of a given Float64 (provided you use enough precision for the BigFloat):

julia> x = Float64(big"0.123456789012345678", RoundUp)
0.12345678901234569

julia> big(x)
1.234567890123456912476740399142727255821228027343750000000000000000000000000000e-01

julia> y = prevfloat(x)
0.12345678901234568

julia> big(y)
1.234567890123456773698862320998159702867269515991210937500000000000000000000000e-01
2 Likes