Scientific notation for large integers in JavaScript
JavaScript will convert integers longer than 21 digits to scientific notation in a string context . If you need to print an integer as part of a URL, how do you prevent the conversion from happening?
Solution
JavaScript provides the Number.toFixed method, but if the number is greater than or equal to 1e21 with a precision of up to 20, it will use scientific notation. Otherwise, you could implement it yourself, but it would be messy.
function toFixed(x) { if (Math.abs(x) < 1.0) { var e = parseInt(x.toString().split('e-')[1]); if (e) { x *= Math.pow(10,e-1); x = '0.' + (new Array(e)).join('0') + x.toString().substring(2); } } else { var e = parseInt(x.toString().split('+')[1]); if (e > 20) { e -= 20; x /= Math.pow(10,e); x += (new Array(e+1)).join('0'); } } return x; }
The above method uses cheap and simple string repetition ((new Array(n 1)).join(str)). You can also define String.prototype.repeat on top of this and use Russian peasant multiplication.
Please note that this answer only applies to displaying large numbers without using scientific notation. For any other case, you should use a BigInt library such as BigNumber, Leemon's BigInt or BigInteger. Additionally, a new native BigInt is coming soon, supported by Chromium and Chromium-based browsers (Chrome, new Edge [late v79], Brave) and Firefox, with support in development for Safari.
Here's how to convert using BigInt: BigInt(n).toString()
Example:
const n = 13523563246234613317632; console.log("toFixed (wrong): " + n.toFixed()); console.log("BigInt (right): " + BigInt(n).toString());
The above is the detailed content of How to Prevent JavaScript from Converting Large Integers to Scientific Notation in Strings?. For more information, please follow other related articles on the PHP Chinese website!