Published
Edited
May 4, 2018
1 star
Insert cell
Insert cell
Insert cell
(2**332).toPrecision(100)
Insert cell
Insert cell
(2**332).toString(2)
Insert cell
Insert cell
renderFullInt(2**1023)
Insert cell
// If the given float has an integer value, use BigNumber.js to render out all the digits.
function renderFullInt(x) {
// NOTE: By default, JS will only print about 15-17 significant digits.
// We can use `.toPrecision(n)` to get exactly n digits, but only n<=100.
// So we use `isSafeInteger` to check if JS can't print a full integer (i.e. when exponent>52)
if (Number.isInteger(x) && !Number.isSafeInteger(x)) {
const floats = new Float64Array([x]);
const bytes = new Uint8Array(floats.buffer);
// sign │ exponent (11 bits) │ mantissa (52 bits)
// ┌─┼─────────────────────┼─────────
// │s│e e e e e e e e e e e│m m m m ...
// ├─┴─────────────┬───────┴───────┬─
// │7 6 5 4 3 2 1 0│7 6 5 4 3 2 1 0│ ...
// └───────────────┼───────────────┼─
// byte 7 │ byte 6 │ ...

const sign = bytes[7] >> 7 ? -1 : 1;
let exponent = ((bytes[7] & 0x7f) << 4 | bytes[6] >> 4) - 0x3ff;
// Our goal is to extract the mantissa as an integer by moving the "floating point" (dot)
// to just after the mantissa. The exponent tells us how far to move the dot from its
// normalized position.
//
// normalized: 1.mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm * 2^e
// integerized: 1mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm. * 2^(e-52)

// We want the 52-bit mantissa as unsigned integer.
// (setting the float's exponent to 52 and its sign to 0 causes the float to evaluate to this)
// (exponent 52 has to be offset by +0x3ff, so 52+0x3ff = 0x433)
bytes[7] = 0x43; // 0100 0011
bytes[6] = 0x30 | (bytes[6] & 0xf); // 0011 XXXX
const uint = floats[0]; // float's value is now exactly equal to the mantissa integer
// Our `exponent` is guaranteed to be >52 (because of our !isSafeInteger precondition above)
// We already moved the floating point over 52 places when extracting our `integer`, so
// we take the remainder exponent, which should still be positive.
const expRemainder = exponent - 52;
console.assert(exponent > 0);

return BigNumber(2).pow(expRemainder).times(uint*sign).toString(10);
}
return String(x);
}
Insert cell
Insert cell
Insert cell
Insert cell
Number.MAX_VALUE.toString(2)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
BigNumber = require('bignumber.js')
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more