Skip to content

Zig Floats

Floats are numbers with a decimal point, like 9.99, -0.5 or 3.14159. You’ll use them for prices in a shopping cart demo, distances, speeds, averages and anything you measure rather than count. Zig’s floats are the same IEEE-754 floats that C, Python, JavaScript and Rust use, so they come with the same famous surprises. This page shows you the types, then the surprises, so they don’t catch you out later.

The two float types you’ll use are f32 (32 bits) and f64 (64 bits):

const std = @import("std");
pub fn main() void {
const third_32: f32 = 1.0 / 3.0;
const third_64: f64 = 1.0 / 3.0;
std.debug.print("f32: {d}\n", .{third_32});
std.debug.print("f64: {d}\n", .{third_64});
}

Output:

f32: 0.33333334
f64: 0.3333333333333333

An f32 keeps about 7 significant digits and an f64 about 16. Look at the last digit of the f32 line: it’s already rounded. Use f64 unless you have a reason not to. It’s what Python’s float and JavaScript’s number are. f32 is common in graphics and games, where you have millions of values and the memory matters more than the last few digits.

Zig also has f16, f80 and f128 for special cases. The Floats section of the reference lists them all.

You can write floats in the usual ways, including scientific notation:

const std = @import("std");
pub fn main() void {
const price = 19.99;
const big = 1.5e6; // 1.5 times 10 to the power 6
const tiny = 2.5e-4;
const speed_of_light = 299_792_458.0;
const whole: f64 = 3; // a whole number literal works for a float too
std.debug.print("{d} {d} {d} {d} {d}\n", .{ price, big, tiny, speed_of_light, whole });
}

Output:

19.99 1500000 0.00025 299792458 3

Like integer literals, a float literal like 19.99 has the type comptime_float until you put it somewhere with a real type. {d} prints a float in plain decimal form and leaves off a trailing .0.

Most of the time you don’t want 16 digits. Add .N after d to round to N places when printing:

const std = @import("std");
pub fn main() void {
const total: f64 = 2.0 / 3.0;
std.debug.print("{d}\n", .{total});
std.debug.print("{d:.2}\n", .{total});
std.debug.print("{d:.0}\n", .{total});
std.debug.print("{e}\n", .{total});
}

Output:

0.6666666666666666
0.67
1
6.666666666666666e-1

{d:.2} rounds to two decimals, which is what you want for money on a receipt. {e} prints scientific notation. Width, padding and the rest are on the Zig Format Strings page.

Here’s the surprise everyone meets once:

const std = @import("std");
pub fn main() void {
const a: f64 = 0.1;
const b: f64 = 0.2;
std.debug.print("{d}\n", .{a + b});
std.debug.print("equal to 0.3? {}\n", .{a + b == 0.3});
}

Output:

0.30000000000000004
equal to 0.3? false

This isn’t a Zig bug. Floats are stored in binary, and 0.1 has no exact binary form, just like 1/3 has no exact decimal form (0.333...). The stored value is a tiny bit off, and the errors add up. Python and JavaScript print the exact same 0.30000000000000004.

The fix is to never test floats with == when they come from math. Check that they’re close enough instead:

const std = @import("std");
pub fn main() void {
const a: f64 = 0.1;
const b: f64 = 0.2;
const close = std.math.approxEqAbs(f64, a + b, 0.3, 1e-9);
std.debug.print("close to 0.3? {}\n", .{close});
}

Output:

close to 0.3? true

std.math.approxEqAbs(f64, x, y, tolerance) is true when x and y differ by at most tolerance. Here that’s 1e-9, one billionth. For values that can be very large or very small, std.math.approxEqRel compares relative to their size instead.

An f32 can’t even hold every whole number. Past 16,777,216 (2 to the power 24) it starts skipping:

const std = @import("std");
pub fn main() void {
var count: f32 = 16_777_216;
count += 1;
std.debug.print("{d}\n", .{count});
}

Output:

16777216

Adding 1 did nothing, because the next number an f32 can store is 16,777,218. This is one more reason to count things with integers and use floats for measurements. Zig even catches the literal version: const x: f32 = 16_777_217; is a compile error, because that exact value can’t be stored.

Floats have a few special values. Dividing a non-zero float by zero doesn’t crash, it gives infinity. And “not a number”, NaN, is the result of nonsense like 0 / 0:

const std = @import("std");
pub fn main() void {
var zero: f64 = 0;
_ = &zero;
const inf = 1.0 / zero;
const nan = std.math.nan(f64);
std.debug.print("{d} {d}\n", .{ inf, -inf });
std.debug.print("is inf? {}\n", .{std.math.isInf(inf)});
std.debug.print("nan == nan? {}\n", .{nan == nan});
std.debug.print("is nan? {}\n", .{std.math.isNan(nan)});
}

Output:

inf -inf
is inf? true
nan == nan? false
is nan? true

NaN is never equal to anything, not even itself, so x == nan is always false. Use std.math.isNan(x) to test for it. Zig has no keyword for these values; you get them from std.math.inf(f64) and std.math.nan(f64). (_ = &zero; keeps zero a runtime value, see Zig Variables. Dividing by a zero the compiler can see is a compile error.)

The most common math operations are builtins, so you don’t need an import:

const std = @import("std");
pub fn main() void {
const x: f64 = 2.7;
const y: f64 = -2.7;
std.debug.print("floor {d}, ceil {d}, round {d}, trunc {d}\n", .{ @floor(x), @ceil(x), @round(x), @trunc(x) });
std.debug.print("trunc of -2.7: {d}, abs of -2.7: {d}\n", .{ @trunc(y), @abs(y) });
std.debug.print("sqrt of 2: {d}\n", .{@sqrt(@as(f64, 2.0))});
std.debug.print("2 to the 10: {d}\n", .{std.math.pow(f64, 2.0, 10.0)});
}

Output:

floor 2, ceil 3, round 3, trunc 2
trunc of -2.7: -2, abs of -2.7: 2.7
sqrt of 2: 1.4142135623730951
2 to the 10: 1024

@floor rounds down, @ceil rounds up, @round goes to the nearest whole number (halves go away from zero), and @trunc just drops the decimals. @as(f64, 2.0) gives the literal a real type, so @sqrt works on an f64 instead of a comptime_float. Trigonometry and logs are builtins too (@sin, @cos, @log, @exp), and more functions and constants, like std.math.pow and std.math.pi, live in std.math.

You’ll often multiply a price by a count. If the integer is small enough that every value fits exactly in the float, Zig converts it for you. A u32 always fits in an f64, so this works:

const std = @import("std");
pub fn main() void {
const price: f64 = 2.5;
var items: u32 = 3;
items += 1;
std.debug.print("total: {d}\n", .{price * items});
}

Output:

total: 10

But a usize or u64 can hold numbers an f64 can’t store exactly, so Zig won’t convert those on its own. That bites when you count things, because counts and lengths are usually usize:

const std = @import("std");
pub fn main() void {
var sum: f64 = 0;
var count: usize = 0;
sum += 2.5;
count += 1;
sum += 4.0;
count += 1;
const average = sum / count;
std.debug.print("{d}\n", .{average});
}
main.zig:10:25: error: incompatible types: 'f64' and 'usize'
const average = sum / count;
~~~~^~~~~~~

The fix is an explicit conversion with @floatFromInt, which turns an integer into a float:

const std = @import("std");
pub fn main() void {
var sum: f64 = 0;
var count: usize = 0;
sum += 2.5;
count += 1;
sum += 4.0;
count += 1;
const average = sum / @as(f64, @floatFromInt(count));
std.debug.print("average: {d}\n", .{average});
}

Output:

average: 3.25

The @as(f64, ...) part tells @floatFromInt which float type you want. It looks wordy, and it is, but you’ll write it often enough that it becomes a habit. Zig Type Casting explains the pattern.

Print 3 x 4.99 = 14.97 from const qty: u32 = 3; and const price: f64 = 4.99;, with exactly two decimals for the money.

Hint: {d:.2} rounds to two decimals. A u32 can be multiplied by an f64 directly.

Show solution
const std = @import("std");
pub fn main() void {
const qty: u32 = 3;
const price: f64 = 4.99;
std.debug.print("{d} x {d:.2} = {d:.2}\n", .{ qty, price, price * qty });
}

Output:

3 x 4.99 = 14.97

price * qty is an f64. Without .2 it could print something like 14.970000000000001, which is the floating-point rounding from this page.

Add 0.1 to a var total: f64 = 0; three times, then print whether it’s exactly 0.3 and whether it’s within 0.000001 of 0.3. Expected output: exact: false, close: true.

Hint: std.math.approxEqAbs(f64, a, b, tolerance).

Show solution
const std = @import("std");
pub fn main() void {
var total: f64 = 0;
total += 0.1;
total += 0.1;
total += 0.1;
const exact = total == 0.3;
const close = std.math.approxEqAbs(f64, total, 0.3, 0.000001);
std.debug.print("exact: {}, close: {}\n", .{ exact, close });
}

Output:

exact: false, close: true

Three small rounding errors add up to a value just above 0.3, so == fails but the tolerance check passes.

Print the area of a circle with radius 2.5, rounded to 2 decimals: area: 19.63. The formula is pi times radius squared.

Hint: std.math.pi is pi, and r * r is r squared.

Show solution
const std = @import("std");
pub fn main() void {
const r: f64 = 2.5;
const area = std.math.pi * r * r;
std.debug.print("area: {d:.2}\n", .{area});
}

Output:

area: 19.63

std.math.pi is a comptime_float, and multiplying it by the f64 radius gives an f64. The exact value is 19.634954…, which .2 rounds to 19.63.

  • Use f64 by default (about 16 digits); f32 (about 7 digits) when memory matters, like in graphics.
  • Print with {d}, or {d:.2} for a fixed number of decimals.
  • Float math is slightly inexact: 0.1 + 0.2 != 0.3. Compare with std.math.approxEqAbs, never ==.
  • Use integers for money and counting, floats for measurements.
  • Dividing a float by zero gives inf; NaN isn’t equal to itself, so test with std.math.isNan.
  • @floor, @ceil, @round, @trunc, @sqrt and @abs are builtins; more is in std.math.
  • Small integers mix with floats directly, but usize and u64 need @floatFromInt.

Next up: Zig Operators, all the math, comparison and bit operators, plus Zig’s wrapping and saturating ones.

Quick check

1. What does 0.1 + 0.2 == 0.3 give for f64 values?
2. How do you print 2.0 / 3.0 as 0.67?
3. How should you check whether x is NaN?
4. Why is sum / prices.len a compile error when sum is an f64?