-
Notifications
You must be signed in to change notification settings - Fork 3
Float
Chung Leong edited this page Feb 11, 2024
·
6 revisions
Floats are used to store numbers with decimal parts. There are five types in Zig: f16
(half-precision), f32
(single-precision), f64
(double-precision), f80
(extended precision), and f128
(quadruple-precision). They are all represented in JavaScript as number
. Because number
is defined by ECMA to be a double-precision float, returning f80
and f128
to JavaScript will result in loss in precision.
const std = @import("std");
pub fn getPi64() f64 {
return std.math.pi;
}
pub fn getPi80() f80 {
return std.math.pi;
}
pub fn getPi128() f128 {
return std.math.pi;
}
import { getPi64, getPi80, getPi128 } from './float-example-1.zig';
console.log(getPi80() === getPi64());
console.log(getPi128() === getPi64());
true
true
Conversely, f32
and f16
can appear to contain more precision than in reality when printed.
const std = @import("std");
pub fn getPi64() f64 {
return std.math.pi;
}
pub fn getPi32() f32 {
return std.math.pi;
}
pub fn getPi16() f16 {
return std.math.pi;
}
import { getPi64, getPi32, getPi16 } from './float-example-2.zig';
console.log(`pi = ${getPi64()}`);
console.log(`pi = ${getPi32()}`);
console.log(`pi = ${getPi16()}`);
pi = 3.141592653589793
pi = 3.1415927410125732
pi = 3.140625
Use toPrecision() to limit the number of digits in the result.
import { getPi64, getPi32, getPi16 } from './float-example-2.zig';
console.log(`pi = ${getPi64()}`);
console.log(`pi = ${getPi32().toPrecision(8)}`);
console.log(`pi = ${getPi16().toPrecision(4)}`);
pi = 3.141592653589793
pi = 3.1415927
pi = 3.141