Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

guys! I have a problem converting an array of strings into floats. If i use map(parseFloat) I get int numbers. Is there a problem with the commas in 40,78, that is why I get 40 when I use the parseFloat function ?

This is the array I want to convert:

[["40,78","6,27","0,00",null,null,null,null,null,null,null,null,null,"35,87",null,null]];

I want to convert it into this:

[[40.78,6.27,0.00,null,null,null,null,null,null,null,null,null,35.87,null,null]];

Does anybody have any idea? Thanks in advance!

share|improve this question
    
But, if you do that and when you check the array length, it will return only 1. – David R Aug 25 at 13:04

It's as you say. parseFloat() considers as float numbers only strings with . character, not ,. Also it returns NaN for null values:

var arr = ["40,78","6,27","0,00",null,null,null,null,null,null,null,null,null,"35,87",null,null];
    
var res = arr.map(function(val) {
  return val ? parseFloat(val.replace(',', '.')) : null;
});

console.log(res);

share|improve this answer

Solution:

function MyCtrl($scope) {
    $scope.array= ["40,78","6,27","0,00",null,null,null,null,null,null,null,null,null,"35,87",null,null]
    for(var i=0; i<$scope.array.length; i++) {
      if ($scope.array[i] !== null) {
            $scope.array[i] = parseFloat($scope.array[i].replace(',','.'))
      }
    }
}

Link: http://jsfiddle.net/p2kpeptq/1/

share|improve this answer
var arr = ["40,78","6,27","0,00",null,null,null,null,null,null,null,null,null,"35,87",null,null];
arr.map(function(v) {
  return v === null ? v : parseFloat(v.replace(",", "."));
});

In your case you have a double array. Depends on your use case if you do an additional .map call or handle the outer array in another way.

share|improve this answer

You have '40,78' comma separated strings, for parsing to float you need to have dot separated strings f.e: '40.78' and map(parseFloat) would work correctly.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.