user4584963
user4584963

Reputation: 2523

Javascript how to return number with x decimal places

For a given integer I want to return a number with that many decimal places. For example const decimals = 5 should return .00001. I tried this 10 ** (-1 * decimals) but instead of .00001 I am getting .00000999999999999999. What is going on here? What is the correct way to do this?

Upvotes: 0

Views: 424

Answers (2)

Majed Badawi
Majed Badawi

Reputation: 28414

This should work:

const decimals = 5;
const res = (1 / 10**decimals).toFixed(decimals);
console.log(res);

Upvotes: 1

Scott Marcus
Scott Marcus

Reputation: 65808

Just use .toFixed(nN).

const decimals = 5;

let num = .0123456789;

console.log(num.toFixed(decimals));

Upvotes: 1

Related Questions