Home > OS >  How to stop Javascript from rounding numbers after 16 decimal places?
How to stop Javascript from rounding numbers after 16 decimal places?

Time:04-18

Let's say I have the following code:

console.log(1 / 3);

It prints "0.3333333333333333".

Is there a way to not have it stop?

(For any curious souls: it's for calcuating Pi)

CodePudding user response:

Use the .toFixed method:

console.log((1/3).toFixed(2))

CodePudding user response:

Write a function whrere the numbers are multiplied with precision before they divided:

function div(num1, num2, prec=100) {
  return (num1*prec)/(num2*prec).toFixed(prec)
}

console.log(div(1,3,100));
console.log(div(11,13,100));

  • Related