Home > Web Front-end > JS Tutorial > How to Prevent JavaScript from Converting Large Integers to Scientific Notation in Strings?

How to Prevent JavaScript from Converting Large Integers to Scientific Notation in Strings?

Barbara Streisand
Release: 2024-12-10 08:59:10
Original
719 people have browsed it

How to Prevent JavaScript from Converting Large Integers to Scientific Notation in Strings?

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;
}
Copy after login

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());
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template