LEVIATHAN v962456e · 962456eee1

Lexical

Numeric literals

Decimal, hexadecimal and binary integers, floats, and the _ digit separator.

since 0.1.0-alpha.1linuxwindowswasm

Description

An integer literal is written in decimal, hexadecimal (0x or 0X) or binary (0b or 0B). There is no octal form: 010 is the decimal number ten. A literal with a fractional part, such as 3.14, is a float.

An underscore may separate digits for readability in any base, including in the fractional digits of a float. It does not change the value.

Integer and float literals

console.writeln(42);
console.writeln(0xFF);
console.writeln(0B1010);
console.writeln(1_000_000);
console.writeln(0x1_FF);
console.writeln(3.14);
console.writeln(1_000.000_5);
console.writeln(010);
console.writeln(0x8000000000000000 == 1 << 63);
Range r = 0xA..0xC;
for (int i in r) {
    console.writeln(i);
}
42
255
10
1000000
511
3.140000
1000.000500
10
true
10
11
12

Rules

  • A literal is decimal, 0x/0X hexadecimal or 0b/0B binary. There is no octal.
  • _ may separate digits in any base. It may not lead, trail or double up: 0x_1F, 1000_ and 1__000 are compile errors.
  • A hexadecimal or binary literal is always an int. 0x1.5 is a compile error, not a fraction. 0xA..0xF is the range operator applied to two hexadecimal integers.
  • A hexadecimal or binary literal uses its full 64-bit pattern, so 0x8000000000000000 is the same value as 1 << 63, which is the smallest int.
  • A float literal needs digits on both sides of the point. There is no exponent form: 1e3 is a syntax error; write 1000.0.
  • A literal has type int or float unless the context asks for a sized numeric type, in which case it is converted and range-checked at compile time (see lang.sized-integers and lang.sized-floats).

Examples

Digit separators in each base, and a hex pattern:

Separators and bases

console.writeln(0b1111_0000);
console.writeln(0xDEAD_BEEF);
console.writeln(0xFF == 255);
console.writeln(1_000 * 3);
240
3735928559
true
3000

Notes

Division of two integer literals is integer division: 7 / 2 is 3. Make one operand a float to get a float result: 7 / 2.0 is 3.500000.

See also