Skip to content

Core\BigInt::toString

$bigInt->toString(): string

Returns this number as text: its digits in base 10, with a leading - when the number is negative.

echo and string interpolation render a Core\BigInt through this method, so echo $number and "{$number}" print exactly what toString returns. You call it yourself when you need the digits as a string: to store them, to send them, or to measure how long the number is.

The text is exact at every size. Nothing is shortened, and no separator is added between the digits, so Core\BigInt::parse reads the text back to the number it came from.

Good to know: for a base other than 10, use format, which writes the same digits in any base from 2 to 36.

Return value

Returns string. The decimal digits. parse reads them back to the same value.

Examples

A number as text

<?nvs
// Shows the digits of a number as a `string`. `echo` prints the same text
// without you calling `toString` yourself.
var $value = Core\BigInt::parse('184467440737095516150');
// Both lines print 184467440737095516150.
echo $value->toString(), "\n";
echo $value, "\n";
// A negative number carries a leading minus sign. This prints
// -184467440737095516150.
echo $value->negated()->toString(), "\n";
// A `Core\BigInt` inside a string is replaced with the same text. This prints
// "balance 184467440737095516150".
echo "balance {$value}", "\n";
Output
184467440737095516150
184467440737095516150
-184467440737095516150
balance 184467440737095516150

The text reads back to the same number

<?nvs
// Shows that the text is exact at every size. `Core\BigInt::parse` reads it
// back to the number it came from.
var $value = Core\BigInt::of(1)->shiftedLeft(200);
// The number has 61 digits. This prints 61.
echo Core\Str::length($value->toString()), "\n";
// Nothing is shortened and no separator is added, so parsing the text gives
// the same number back. `compareTo` returns 0 for two numbers that are equal.
echo Core\BigInt::parse($value->toString())->compareTo($value), "\n";
// The minus sign reads back as well. This prints 0.
echo Core\BigInt::parse($value->negated()->toString())->compareTo($value->negated()), "\n";
Output
61
0
0

Sending a number that json cannot carry

<?nvs
// Shows a program writing large numbers into a message. A JSON number cannot
// carry this many digits exactly, so each one is sent as text.
var $account = Core\BigInt::parse('184467440737095516159999');
var $balance = Core\BigInt::parse('-250000000000000000000');
// `toString` gives the digits as a `string`. That is what goes into the
// message, so both numbers keep every digit.
echo '{"account":"', $account->toString(), '","balance":"', $balance->toString(), '"}', "\n";
Output
{"account":"184467440737095516159999","balance":"-250000000000000000000"}