Keep decimals

0

I want to keep the decimals, I have a long number 120.29998999867869 and I want to cut it with 5 decimals, the desired result is 120.299998 , the following code I try but I get 120.30000

let num = 120.29999999867869;
console.log(num.toFixed(5));
    
asked by x-rw 10.10.2018 в 22:51
source

1 answer

3

In the example that you are giving, the rounding is done towards .30000 since it is not the same number that you raise in the question.

If you want decimals to be seen without rounding, you can do the following:

let num = 120.29999999867869;
num.toString().split('.')[0] + '.' + num.toString().split('.')[1].substring(0,5);

However, it is a not so attractive solution.

I include examples:

// Número usado en la pregunta
let num1 = 120.29998999867869
console.log('Numero usado en la pregunta: ' + num1.toFixed(5));

// Número usado en el ejemplo
let num2 = 120.29999999867869;
console.log('Numero usado en el ejemplo: ' + num2.toFixed(5));
console.log('Numero usado en el ejemplo (con split y substring): ' + num2.toString().split('.')[0] + '.' + num2.toString().split('.')[1].substring(0,5));
    
answered by 10.10.2018 / 23:36
source