Decimals without rounding in javascript

Asked

Viewed 2,123 times

2

How would you get the following result.

I want to decrease a number of decimals after the comma without the number rounding ? ex: 5,8608 --> 5,860

I have tested several functions and forms but all rise the number to 5,861.

From now on I thank those who can contribute.

1 answer

5


I did something similar here at Sopt but I can’t find... :(

Here is another suggestion. Multiply the numbers you want by the order of magnitude equal to the number of decimals. Then you take the decimal part and divide again by the same order of magnitude. Something like this:

function ajuste(nr, casas) {
  const og = Math.pow(10, casas)
  return Math.floor(nr * og) / og;
}

console.log(ajuste(3.456, 2)); // 3.45
console.log(ajuste(4.123, 2)); // 4.12

Browser other questions tagged

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