Home > Net >  How to divide BigInt by decimal in Javascript?
How to divide BigInt by decimal in Javascript?

Time:03-28

I have this code below:

let n = 100n;
let x = 0.1;

console.log(n/x); // Throws error

Error:

TypeError: Cannot mix BigInt and other types, use explicit conversions

How do I divide a BigInt by a decimal value in JavaScipt?

CodePudding user response:

In general...

...mixing number and BigInt is asking for trouble, which is why no math operators will let you do it and explicit conversion is required.

(Note: Decimal is on the horizon, which will apply here when it matures.)

If you want a number result...

...convert the BigInt to a number before doing the calculation; beware that the conversion may be lossy for very large numbers (this is the point of BigInt), specifically numbers above Number.MAX_SAFE_INTEGER or below Number.MIN_SAFE_INTEGER:

let n = 100n;
let x = 0.1;
let result = Number(n) / x;
console.log(result);

If you want a BigInt result...

...it's more complicated, because you have to decide what to do with a fractional result. (Your example won't have a fractional result, but the general case will.) You could go through number, but again that's a potentially lossy operation:

let n = 100n;
let x = 0.1;
let result = BigInt(Number(n) / x); // Throws if the result is fractional
// let result = BigInt(Math.round(Number(n) / x)); // Rounds instead of throwing
console.log(result.toString());

If you can refactor the operation so you can express it in whole numbers, that makes it a lot easier, because then you can make x a BigInt. For instance, in your specific case, / 0.1 is the same as * (1 / 0.1) which is * 10:

let n = 100n;
let x = 10n;
let result = n * x;
console.log(result.toString());

...but that's just that specific case.

You'll probably find you need to handle it on a case-by-case basis, trying to avoid doing the operation. When you can't, and the divisor is fractional, a round-trip through number may be unavoidable.

CodePudding user response:

Just Convert the bigint to number. It will Work.

let n = 100n;
let x = 0.1;
console.log(Number(n)/x); 

It will Return Result 1000

  • Related