Zig Floats & Casting
Floating-point numbers hold fractional values such as 3.75 or -0.001. This lesson covers the float types and, just as importantly, how to convert between numeric types — because Zig never converts numbers behind your back when information could be lost.
Float types
| Type | Bits | Precision (approx.) |
|---|---|---|
f16 |
16 | 3 decimal digits |
f32 |
32 | 7 decimal digits |
f64 |
64 | 15–16 decimal digits (the usual choice) |
f80 |
80 | x87 extended precision |
f128 |
128 | 33 decimal digits |
A float literal such as 2.5 has type comptime_float until it is given a concrete type.
const std = @import("std");
pub fn main() void {
const price: f64 = 19.99;
const qty: f64 = 3;
const total = price * qty;
std.debug.print("total: {d}\n", .{total});
std.debug.print("rounded: {d:.2}\n", .{total});
std.debug.print("sqrt(2) = {d:.5}\n", .{@sqrt(@as(f64, 2.0))});
std.debug.print("floor/ceil: {d} {d}\n", .{ @floor(@as(f64, 2.7)), @ceil(@as(f64, 2.1)) });
}total: 59.97
rounded: 59.97
sqrt(2) = 1.41421
floor/ceil: 2 3
Note: Floats are approximations.
0.1 + 0.2is not exactly0.3in binary floating point — compare floats with a tolerance, for example@abs(a - b) < 1e-9, rather than with==.
Safe automatic conversions
Zig widens a number automatically only when every possible value fits in the new type. This is called type coercion:
const small: u8 = 200;
const bigger: u32 = small; // ok: every u8 fits in u32
const signed: i16 = small; // ok: every u8 fits in i16
const f: f64 = @as(f32, 1.5); // ok: f32 -> f64Going the other way — u32 to u8, or i32 to u32 — does not happen automatically. You must use a cast builtin and thereby state what you expect.
Cast builtins
| Builtin | From → To | If the value doesn't fit |
|---|---|---|
@intCast(x) |
integer → smaller/other integer | panic in safe modes |
@truncate(x) |
integer → smaller integer | keeps the low bits (by design) |
@floatFromInt(x) |
integer → float | always works |
@intFromFloat(x) |
float → integer (drops the fraction) | panic in safe modes |
@floatCast(x) |
float → smaller float | rounds |
@as(T, x) |
any safe coercion, made explicit | compile error |
@intFromBool(b) |
bool → u1 |
— |
@bitCast(x) |
reinterpret the same bits as another type | sizes must match |
These builtins take the target type from the context — the type of the variable you assign to, or an @as around them:
const std = @import("std");
pub fn main() void {
const big: i32 = 200;
const as_byte: u8 = @intCast(big); // fits, so it's fine
const huge: u32 = 0x1234_5678;
const low_bits: u8 = @truncate(huge); // keeps 0x78
const count: usize = 7;
const half = @as(f64, @floatFromInt(count)) / 2.0;
const temp: f64 = 36.9;
const whole: i32 = @intFromFloat(temp); // fraction dropped
std.debug.print("{d} 0x{x} {d} {d}\n", .{ as_byte, low_bits, half, whole });
}200 0x78 3.5 36
Without a known target type, the cast does not know what to produce:
const std = @import("std");
pub fn main() void {
const n: u32 = 9;
const f = @floatFromInt(n);
std.debug.print("{d}\n", .{f});
}./example.zig:5:15: error: @floatFromInt must have a known result type
const f = @floatFromInt(n);
^~~~~~~~~~~~~~~~
./example.zig:5:15: note: use @as to provide explicit result type
Mixing integers and floats
Arithmetic needs both operands to have the same type. To compute an average of integers, convert first:
const std = @import("std");
pub fn main() void {
const scores = [_]u32{ 7, 9, 8, 10 };
var sum: u32 = 0;
for (scores) |s| sum += s;
const avg = @as(f64, @floatFromInt(sum)) / @as(f64, @floatFromInt(scores.len));
std.debug.print("sum={d} avg={d:.2}\n", .{ sum, avg });
const percent: u8 = @intFromFloat(@round(avg * 10.0));
std.debug.print("percent={d}\n", .{percent});
}sum=34 avg=8.50
percent=85
Inspecting bits
@bitCast keeps the bytes exactly as they are and just reads them as another type of the same size — useful when working with file formats or hardware registers:
const std = @import("std");
pub fn main() void {
const x: f32 = 1.0;
const bits: u32 = @bitCast(x);
const minus_one: i8 = -1;
const unsigned: u8 = @bitCast(minus_one);
std.debug.print("1.0 as bits: 0x{x}\n", .{bits});
std.debug.print("-1 as u8: {d}\n", .{unsigned});
}1.0 as bits: 0x3f800000
-1 as u8: 255
Test yourself
Which conversion happens automatically?
- u32 to u8
- i32 to u32
- u8 to u32
- f64 to i64
What does @truncate do when converting 0x1234 to u8?
- Panics
- Returns 0x12
- Returns 0x34
- Returns 255
Why does const f = @floatFromInt(n); fail to compile?
- n must be a float
- The cast has no known result type
- @floatFromInt does not exist
- Floats cannot be const