1

I have a string of numbers when i do svg.getAttribute("d") in the console:

"-0.05990783410138251,0.13594470046082952,-0.06912442396313362,0.14976958525345618,-0.07603686635944701,0.15668202764976957,-0.08755760368663595,0.16589861751152069,-0.09677419354838718,0.16820276497695852,-0.10599078341013829,0.16820276497695852,-0.12211981566820279,0.16820276497695852,-0.13594470046082957,0.16820276497695852,-0.14055299539170513,0.16820276497695852,-0.14516129032258068,0.16589861751152069,-0.1474654377880184"

I want this to be converted to a float so i did parseFloat(svg.getAttribute("d")) but all i get is the first number back:

-0.05990783410138251

How can i get all the numbers?

Thanks

  • You can't convert a string of number**s**, plural, to "a float", singular, unless you pick one of the numbers and ignore the rest. If your desired result is an array of numbers please [edit] the question to say so. – nnnnnn Nov 03 '17 at 02:01

4 Answers4

2

Using String.prototype.split() and Array.prototype.map() you can get an array of float values as follows:

const values = '-0.05990783410138251,0.13594470046082952,-0.06912442396313362,0.14976958525345618,-0.07603686635944701,0.15668202764976957,-0.08755760368663595,0.16589861751152069,-0.09677419354838718,0.16820276497695852,-0.10599078341013829,0.16820276497695852,-0.12211981566820279,0.16820276497695852,-0.13594470046082957,0.16820276497695852,-0.14055299539170513,0.16820276497695852,-0.14516129032258068,0.16589861751152069,-0.1474654377880184';

const floats = values.split(',').map(parseFloat);

console.log(floats);
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • 1
    It should be safe to say `.map(parseFloat)` shouldn't it? (Unlike `.map(parseInt)`, which doesn't do the right thing.) – nnnnnn Nov 03 '17 at 02:04
1

You can first split the string by ',' using split() function and then can apply parseFloat().

m00n
  • 1,977
  • 2
  • 13
  • 25
0

You need to convert it to an array of strings first, then you can parse each of them individually. Something like this:

var str = svg.getAttribute("d");
var strNums = str.split(',');
var nums = strNums.map(function (num) {
    return parseFloat(num);
});
0
const numArray = thatStringOfNumbers.split(',').map((num) => parseFloat(num))
SamVK
  • 3,077
  • 1
  • 14
  • 19