Zig Tutorial #5 — Type Conversion
1 min readMar 24, 2021
I met some issues in conversion between integer and float and here are the summary I got from some experiments in case you have the same problem.
First, the easy one:
pub fn main() anyerror!void {
const stdout = std.io.getStdOut().writer(); const x:i32 = 1;
var y:f32 = @as(f32, x); try stdout.print("{}\n", .{y}); // -> 1.0e+00
}
If you put the conversion in a function, it will not work:
fn conversion(i: i32) f32 {
var k = @as(f32, i); // -> error: expected type 'f32', found 'i32'
return k;
}pub fn main() anyerror!void {
const stdout = std.io.getStdOut().writer(); const x:i32 = 1;
var y:f32 = @as(f32, x);
var z:f32 = conversion(x); try stdout.print("{}\n", .{y});
try stdout.print("{}\n", .{z});
}
But if you use @comptime
on function arguments, it will work:
fn conversion(comptime i: i32) f32 {
var k = @as(f32, i); // -> no error
return k;
}pub fn main() anyerror!void {
const stdout = std.io.getStdOut().writer(); const x:i32 = 1;
var y:f32 = @as(f32, x);
var z:f32 = conversion(x); try stdout.print("{}\n", .{y}); // -> 1.0e+00
try stdout.print("{}\n", .{z}); // -> 1.0e+00
}
If you do not want to use comptile
, try @intToFloat()
instead:
fn conversion(i: i32) f32 {
var k = @intToFloat(f32, i);
return k;
}pub fn main() anyerror!void {
const stdout = std.io.getStdOut().writer(); const x:i32 = 1;
var y:f32 = @as(f32, x);
var z:f32 = conversion(x); try stdout.print("{}\n", .{y});
try stdout.print("{}\n", .{z});
}
I cannot explain these results correctly. Please read the Zig documentation for clues.