简体   繁体   中英

How to format (really) big numbers in Javascript?

I want something like the library JavaScript BigNum and Numeral.js working together.

In Numeral.js, I can use strings like this:

var number = numeral('1110000000000000000000000000000000000000000000000000011100000000000000000011111111100');

but the result of number.format(); is really disappointing:

"1.11e+84"

Any way to format a (really) big number nicely?

EDIT: I don't want just avoid scientific notation, it was a wrong assumption. I want to "nicely" format, as I want, for example:

var number = numeral(1000);
numeral.defaultFormat('$0,0.00');

number.format();
// '$1,000.00'

Well, if the number is big:

var number = numeral('100000000000000000000000000');
"$9.999999999999999e+25"

This is a mess. I know JavaScript can't handle big numbers, but my question is exactly because that! I would like a library or a possible solution to this problem.

If you are supporting only recent browsers , I think it might be enough for you to just use Intl.NumberFormat .

Although you it lose precision on big numbers, it will help you show big numbers and currencies pretty easily:

 var number = 1234567890123456789012345678901234567890; console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number)); // → 1.234.567.890.123.460.000.000.000.000.000.000.000.000,00 € console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number)); // → ¥1,234,567,890,123,460,000,000,000,000,000,000,000,000 

You can use Intl.NumberFormat.prototype.format, String.prototype.slice(), String.prototype.concat()

var number = 2.9364136545300044e+24;
var n = new Intl.NumberFormat().format(number);
var res = n.slice(0, 9).concat(".").concat(n.slice(10, 12));
console.log(res);

If you want numbers like '1110000000000000000000000000000000000000000000000000011100000000000000000011111111100' to be handled and printed without precision lost you can:

  1. Store this number as a string and never convert into number. The disadvantage is clear here: you will be not able perform arithmetic operations with numbers in string representation.

  2. You can use one of big numbers library, eg big-numbers ( https://www.npmjs.com/package/big-numbers ). This will allow you to perform calculations and do not lost precision.

Example code:

var bn = new BugNumbers();
var longNumber = bn.of('1110000000000000000000000000000000000000000000000000011100000000000000000011111111100');

var longNumberPlusOne = longNumber.add(1);

// Should pring1110000000000000000000000000000000000000000000000000011100000000000000000011111111101
console.log(bn.format(longNumberPlusOne));

Check documentation for details: http://www.bignumbers.tech

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM