How to Avoid Scientific Notation for Large Numbers in JavaScript

How to avoid scientific notation for large numbers in JavaScript?

There's Number.toFixed, but it uses scientific notation if the number is >= 1e21 and has a maximum precision of 20. Other than that, you can roll your own, but it will 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;
}

Above uses cheap-'n'-easy string repetition ((new Array(n+1)).join(str)). You could define String.prototype.repeat using Russian Peasant Multiplication and use that instead.

This answer should only be applied to the context of the question: displaying a large number without using scientific notation. For anything else, you should use a BigInt library, such as BigNumber, Leemon's BigInt, or BigInteger. Going forward, the new native BigInt (note: not Leemon's) should be available; Chromium and browsers based on it (Chrome, the new Edge [v79+], Brave) and Firefox all have support; Safari's support is underway.

Here's how you'd use BigInt for it: BigInt(n).toString()

Example:

const n = 13523563246234613317632;console.log("toFixed (wrong): " + n.toFixed());console.log("BigInt (right):  " + BigInt(n).toString());

Why JS uses scientific (exponential) notation?

In Javascript, numbers are always stored as floating point numbers and follow IEEE 754's format. As for displaying numbers, Javascript uses ECMAScript display algorithm as mentioned by Dancrumb, which defines when to start rendering numbers in scientific notation format.

If you'd like to avoid scientific notation for large numbers, there are ways to get around it which are discussed in this post: How to avoid scientific notation for large numbers in JavaScript?.

How to prevent large textfield numbers from getting converted into 1e notation -Javascript/EXTJS

If you just want a textfield that allows the user to type a long string of digits without any formatting you could use a textfield with maskRe. This will allow the user to only type characters that match the regular expression in the mask.

Ext.create('Ext.form.Panel', {
renderTo: Ext.getBody(),
items: [{
xtype: 'textfield',
fieldLabel: 'Number',
maskRe: /[0-9]/
}]

});

see fiddle here



Related Topics



Leave a reply



Submit