'How to convert my Array elements to numbers without deleting zero at the end [duplicate]

I want to convert my Array from this :

[ '0.500000', '0.333333', '0.166667' ]

to this :

[ 0.500000, 0.333333, 0.166667 ]

I tried +, Number, parseInt, parseFloat but none of them work.



Solution 1:[1]

As noted in the comments - you cannot retain the zero at the end unless it remains a string - if you convert the array values to numbers - you will lose all trailing zero's. If you need t o perform calculations - then you need to parse the strings into numbers when performing the calculation

but there is a workaround - if all the numbers have the same decimal places - you can use Math.pow() to multiply them by that power to get actual numbers.

This will convert your string array into a number array but with the numbers being mutiplied by 1 * (10 * the number of decimal places).

You can then use the values for performing calculations or whatever you need - just remember to divide by that 100000 to use them. Note that the toFixed() will convert the number to a string and provide the trailing zeros based on the number of decimal places you require.

That said - this is a hacky workaround - I would simply convert them to numbers, perform my calculation and then pad the trailing zeros with toFixed(decimalPlaces). Simple is always best.

const arr = [ '0.500000', '0.333333', '0.166667' ];

const decimalPlaces = 6;

const numArr = arr.map(x => x * (1 * Math.pow(10, decimalPlaces)));



console.log(numArr);
  // gives [500000, 333333, 166667]

const stringArr = numArr.map(y => (y / (1 * Math.pow(10, decimalPlaces))).toFixed(decimalPlaces)) 

console.log(stringArr);
  // gives ["0.500000","0.333333","0.166667"]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1