0

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!

1
  • But, if you do that and when you check the array length, it will return only 1. Commented Aug 25, 2016 at 13:04

4 Answers 4

2

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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/

Comments

0
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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.