Wilt
Wilt

Reputation: 44422

Parse a string representing an array of floats

I have a string as such:

string = "[x,y,z]"

Where x, y and z are valid javascript floats as strings. Some examples:

-0.9999
1.
1.00000000000E-5
-1E5

What is the most efficient (fastest) way to parse this string into an actual javascript array of floats without using Eval?

Now I do this:

parseFloatArray = function(string){
    // isolate string by removing square brackets
    string = string.substr( 1, string.length-2 )

    // create array with string split
    var array = string.split(',');

    // parse each element in array to a float
    for (var i = 0, il = array.length; i < il; i++){
        array[i] = parseFloat(array[i]);
    }

    // return the result
    return array
}

It is important that the solution works correctly for the above examples.

I also tried with JSON.parse which seemed perfect at first, but it returns a SyntaxError for the second example 1. where there is nothing following the decimal separator.

I prepared a fiddle for testing.

Upvotes: 2

Views: 615

Answers (5)

Vishwa
Vishwa

Reputation: 134

Instead of you writing the for loop, you can always use the javascript built in array.prototypes

var string = "[1.,-0.9999,-1.00000E-5]";
var array = string.substr( 1, string.length-2 ).split(',');

console.log(array.map(function(i){return parseFloat(i);}));

you can also use the unary operator instead of parseFloat().

console.log(array.map(function(i){return +i;}));

Upvotes: 0

limekin
limekin

Reputation: 1944

Try this :

str = "[-0.9999, 1., 1.00000000000E-5,-1E5]";
str.slice(1, str.length-1).split(',').map(Number);
// [-0.9999, 1, 0.00001, -100000]

Upvotes: 1

parseFloat basic syntax is parseFloat(string). https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseFloat

If you think the input values are only numbers you can use Number(x) rather than parseFloat.

Also, you might get different values upon parsing because all floating-point math is based on the IEEE [754] standard. so use toPrecision() method to customize your values- https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Number/toPrecision.

Upvotes: 0

Cyril Cherian
Cyril Cherian

Reputation: 32327

Instead of this

array[i] = parseFloat(array[i]);

try array[i] = +array[i];

Above handles all the test cases pretty well.

Here is the working fiddle

Upvotes: 2

PRDeving
PRDeving

Reputation: 669

Most efficient to extract is replacing and splitting.

var str = "[312.413,436.6546,34.1]"; // string

str = () => str.replace(/\[|\]/g, "").split(","); //[312.413, 4...] Array

most eficient to parse is just preceed the string with a "+", that will numerify it and, since javascript works with floats as primitives (and not integers), they will be automatically parsed.

var a = "1.00000000000E-5";
console.log( +a ); // 0.00001

Upvotes: -1

Related Questions