0

I need to format somehow big numbers by country. Intl Api allows us to format only limited ones.

So if I have a long number 12312312312131212312312325444446 I need to map it on Number type and the result is as follows:

const LongNumber = '12312312312131212312312325444446';

console.log(new Intl.NumberFormat('EN').format(Number(LongNumber))); //12,312,312,312,131,213,000,000,000,000,000

I need 12,312,312,312,131,213,000,000,000,000,000 to be 12,312,312,312,131,212,312,312,325,444,446

I'm using mathjs to handle big numbers and the output is BigNumber type but I couldn't find lib to handle the formatting.

The output of mathjs:

{
  d: [1231, 2312312, 1312123, 1231232, 5444446];
  e: 31;
  s: 1;
}

I tried BigInt, but I need to cover all float cases so negative numbers too.

Malpie
  • 11
  • 2
  • Use [`BigInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) instead of `Number`. You're exceeding the capacity of the `number` type, but `BigInt` is designed for very large numbers like these. If you switch `Number` to `BigInt` in the above, it fixes the problem: https://jsfiddle.net/tjcrowder/vtgsknhm/ – T.J. Crowder Mar 02 '23 at 10:39
  • `BigInt` solution is only for Int and positive numbers. I need to cover all float cases. – Malpie Mar 06 '23 at 08:17
  • *"`BigInt` solution is only for Int..."* true *"...and positive numbers"* false, `BigInt` values can be negative. But yes, it's for integers (hence the name). There's a [decimal equivalent in the works](https://github.com/tc39/proposal-decimal). In the meantime, if you search for "JavaScript big decimal" and similar, you'll find existing libraries. – T.J. Crowder Mar 06 '23 at 08:38

0 Answers0