How to define a petabyte constant in JavaScript

1 Answer

0 votes
/*
    JavaScript numbers are 64‑bit floating‑point (IEEE‑754).
    They can represent all integers exactly up to 2^53 (≈ 9e15).

    A petabyte fits safely:

        1 PiB = 2^50  = 1,125,899,906,842,624 bytes
        1 PB  = 10^15 = 1,000,000,000,000,000 bytes

    So both can be represented exactly as normal JavaScript numbers.
*/

// Binary petabyte (pebibyte), using a bit shift.
// (1 << 50) = 2^50 bytes.
// const PETABYTE_PIB = 1 << 50; // Error // bit‑shifts only work on 32‑bit integers

const PETABYTE_PIB = 2 ** 50;        // or: 1n << 50n
// const PETABYTE_PIB = 1n << 50n;   // exact 2^50 as BigInt

// Decimal petabyte (SI petabyte), using a readable numeric literal.
// JavaScript supports underscores for digit grouping.
const PETABYTE_PB = 1_000_000_000_000_000;

console.log("1 PiB =", PETABYTE_PIB, "bytes");
console.log("1 PB  =", PETABYTE_PB, "bytes");



/*
run:

1 PiB = 1125899906842624 bytes
1 PB  = 1000000000000000 bytes

*/

 



answered May 3 by avibootz
...