[Chartjs]-How to convert an array of strings to float in Javascript

9๐Ÿ‘

โœ…

Assuming you have an array in a string format, you can use the following regex to match all the decimals and then use .map(Number)

const str = "['6.35', '2.72', '11.79', '183.25']",
      array = str.match(/\d+(?:\.\d+)?/g).map(Number)

console.log(array)

5๐Ÿ‘

\d matches only digits, itโ€™s the short for [0-9]. For example, in 6.35 \d+ matches 6 and then 35 separately and the dot is ignored. What you get in result is array containing those matches.

As suggested in other answers, use of match is redundant in your case and you can go with:

array.map(Number) 

4๐Ÿ‘

You could just map numbers.

var array = ['6.35', '2.72', '11.79', '183.25'],
    numbers = array.map(Number);

console.log(numbers);

2๐Ÿ‘

Map over the array with the Number function, it will handle the conversion:

console.log(['6.35', '2.72', '11.79', '183.25'].map(Number));

If you want commas in your numbers, then you must stick with a string representation.

See this SO answer about a similar problem with ChartJS.

1๐Ÿ‘

var num = ['6.35', '2.72', '11.79', '183.25'].map(num => Number(num));

console.log(num);

Number() mdn

1๐Ÿ‘

Parse the values to float :

console.log(['6.35', '2.72', '11.79', '183.25'].map(i => parseFloat(i)));

If for some reason .map() doesnโ€™t work just use a loop :

var array = ['6.35', '2.72', '11.79', '183.25']
var x = 0;
var len = array.length
while(x < len){ 
    array[x] = parseFloat(array[x]); 
    x++
}

console.log(array)

0๐Ÿ‘

var arr = ["6,35,2,72,11,79,183,25"]
var result=arr.map(Number);
result[]
typeof(result[])

0๐Ÿ‘

I was having the same problem this is a solution i found
i had

x = "11,1.1,100,100,2,3333,99"

and i wanted

x = [11,1.1,100,100,2,3333,99]

hereโ€™s my solution

x.toString().replace(/, +/g, ",").split(",").map(Number)

Leave a comment