I have a couple of arrays of numbers that are in string format, like:
A = ["1046.7779999999038", "1106.244999999035", "833.5839999999735"]
I want to use the numbers in number format further for some calculations and need them in numeric format, so that I have an array of numbers.
I wanted to use parseInt, but this is not quite right it seems. Maybe I need to split my array first? Ideally I want a function that has an array as input and converts it to the same array in numeric format.
Can somebody help me with this?
6 Answers 6
You use the parseFloat function for parsing floating point numbers.
You can use the map method to parse all of the strings in the array into an array of numbers:
A = $.map(A, function(s){ return parseFloat(s); });
6 Comments
.each() seems more appropriate here since you can just assign to the existing array rather than create a whole new array.each callback, so you have to access the array by index anyway..each() or for are both fine and better than $.map() IMO.map method is intended for, it's up to you if you don't want to use it.You can call parseFloat() on each member of the array.
Comments
Use parseFloat:
function convert(arr){
var ret=[];
for(i in arr){
ret.push (parseFloat(I));
}
return ret;
}
Comments
As others have said, parseFloat() is the conversion function you want to use. To convert your array in place without creating a new temporary array, you can either use a for loop or the .forEach() iterator to cycle through the array and convert the elements in place:
for (var i = 0; i < A.length; i++) {
A[i] = parseFloat(A[i]);
}
or
A.forEach(function(value, index) {
A[index] = parseFloat(value);
});
Comments
Let a separate array B store all your number conversions.
var convert = function() {
for(var i=0;i<A.length< i++){
B[i]=Number(A[i]);
}
}
Comments
Try
$.each(A, function(i, el) {
A[i] = Number(el)
});
var A = ["1046.7779999999038", "1106.244999999035", "833.5839999999735"];
$.each(A, function(i, el) {
A[i] = Number(el)
});
console.log(typeof (A[0] && A[1] && A[2]) === "number", A)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>