Decimal places in Javascript

Asked

Viewed 312 times

3

I’m new to programming, I ran a division account and I wanted to reduce the decimals.

Follow my code below!

document.write("A média de gerações que se passaram é: " + (2019/28));

Obs: Result 72.10714285714286.

I wanted to reduce that number to two houses only, as I do?

Thanks in advance!

2 answers

9

You can use the .toFixed() to limit the decimal places:

const nr = 72.10714285714286;

console.log(nr.toFixed(2)); // dá 72.11
console.log(nr.toFixed(4)); // dá 72.1071

If you want to use in number format (and not String as the .toFixed returns) can convert back to Number with Number... that is to say:

const nr = 72.10714285714286;

console.log(typeof nr); // number
console.log(nr.toFixed(2)); // dá 72.11
console.log(nr.toFixed(4)); // dá 72.1071

console.log(typeof nr.toFixed(2)); // string

const arredondado = Number(nr.toFixed(2));
console.log(typeof arredondado, arredondado); // number 72.11

4

Browser other questions tagged

You are not signed in. Login or sign up in order to post.