Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an array of strings to float in Javascript

I have this array and it is formatted as string:

['6.35', '2.72', '11.79', '183.25']

The problem is that when I convert it to numbers (using - without double quotes ) array.match(/\d+/g).map(Number) || 0;

it changes the dots used for decimals to commas. Then I end up with this new array:

6,35,2,72,11,79,183,25

So, instead of having 4 items inside the array, now I have 8 items, as my delimiters are commas.

Any ideas of how I can convert this array without replacing the dots?

like image 881
Julio S. Avatar asked Dec 03 '22 10:12

Julio S.


1 Answers

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)
like image 87
adiga Avatar answered Mar 15 '23 12:03

adiga