Skip to content

Core\BigInt::format

$bigInt->format({radix?: uint}): string$bigInt->format(
    {radix?: uint},
): string

Writes this number as text in the base you choose, and returns that text as a string.

The base is a whole number from 2 to 36. The digits above 9 are the lower case letters a to z, so base 16 writes 255 as ff. A negative number gets one - in front of it. Without the radix option the base is 10, which gives the same text as toString.

Core\BigInt::parse reads back what format writes, as long as you give it the same base. You can use that pair to keep a very large number in a file, a database column or a web address, and read it back later with nothing lost.

Good to know: a base below 2 or above 36 throws a LogicError. There are ten digits and 26 letters, so 36 is the largest base this class can write.

Options

  • radixuintoptionalThe base to write in, from 2 to 36. The default is 10.

Return value

Returns string. The digits, with a leading - when this value is negative.

Errors

  • LogicErrorradix is outside 2 to 36.

Examples

Writing a number in base 16

<?nvs
// Shows how to write a very large number as text in base 16 and in base 10.
var $value = Core\BigInt::parse('123456789012345678901234567890');
// `format` with `radix: 16` writes the number in base 16. This prints
// 18ee90ff6c373e0ee4e3f0ad2.
echo $value->format({ radix: 16 }), "\n";
// Without the option the base is 10. These two lines print the same text.
echo $value->format(), "\n";
echo $value->toString(), "\n";
Output
18ee90ff6c373e0ee4e3f0ad2
123456789012345678901234567890
123456789012345678901234567890

The same number in several bases

<?nvs
// Shows one number written in four different bases.
var $value = Core\BigInt::ofUint(255);
array<uint> $bases = [2, 8, 16, 36];
// Each line prints the base and the text `format` gives for it. The four texts
// are 11111111, 377, ff and 73.
foreach ($bases as uint $base) {
echo 'base ', $base, ': ', $value->format({ radix: $base }), "\n";
}
Output
base 2: 11111111
base 8: 377
base 16: ff
base 36: 73

A short code for an order number

<?nvs
// Shows how to turn a long order number into a short code a customer can type.
// Base 36 uses the digits and the letters, so the code is shorter than the
// number it stands for.
var $orderNumber = Core\BigInt::parse('9007199254740993');
// `format` with `radix: 36` writes the code. This prints 2gosa7pa2gx.
string $code = $orderNumber->format({ radix: 36 });
echo $code, "\n";
// `Core\BigInt::parse` reads the code back when you give it the same base.
// This prints 9007199254740993.
echo Core\BigInt::parse($code, { radix: 36 }), "\n";
Output
2gosa7pa2gx
9007199254740993