Zig: @floatCast throws error instead of losing precision.

Created on 9 Jul 2020  路  4Comments  路  Source: ziglang/zig

Given this code

const std = @import("std");

pub fn main() anyerror!void {
    const double: f64 = 0.001534;
    const single: f32 = @floatCast(f32, double);

    std.debug.warn("{} {}\n", .{ double, single });
}

Expected result is that it compiles and prints slightly different values (1.53400003e-03 and 1.534e-03)
Actual result is this error:

$ zig build run
./src/main.zig:6:41: error: cast of value 0.001534 to type 'f32' loses information
    const single: f32 = @floatCast(f32, double);
                                        ^
./src/main.zig:6:25: note: referenced here
    const single: f32 = @floatCast(f32, double);
                        ^

The docs say "This cast is safe, but may cause the numeric value to lose precision." Since there doesn't seem to be another way to convert between float types (@trunc, @round, and @truncate all produce integers) I think this is a bug in the implementation, not the documentation.

bug stage1

Most helpful comment

This is regression in master branch.

$ zig version
0.6.0
$ ./i5832
1.534e-03 1.53400003e-03

All 4 comments

This is regression in master branch.

$ zig version
0.6.0
$ ./i5832
1.534e-03 1.53400003e-03

Looks like it was broken in c026a9f6d254cb4b6cf5d75105f17e3c912e32c2
It also looks like it might have been intentional. @Vexu care to weigh in?

Not intentional, just used the wrong cast function.

Reverted (temporarily) due to test failures

Was this page helpful?
0 / 5 - 0 ratings