How to convert an array of strings to float in Javascript - javascript

I have this array and it is formatted as string:
['6.35', '2.72', '11.79', '183.25']
The problem is that when I convert it to numbers (using - without double quotes )
array.match(/\d+/g).map(Number) || 0;
it changes the dots used for decimals to commas. Then I end up with this new array:
6,35,2,72,11,79,183,25
So, instead of having 4 items inside the array, now I have 8 items, as my delimiters are commas.
Any ideas of how I can convert this array without replacing the dots?

Assuming you have an array in a string format, you can use the following regex to match all the decimals and then use .map(Number)
const str = "['6.35', '2.72', '11.79', '183.25']",
array = str.match(/\d+(?:\.\d+)?/g).map(Number)
console.log(array)

\d matches only digits, it's the short for [0-9]. For example, in 6.35 \d+ matches 6 and then 35 separately and the dot is ignored. What you get in result is array containing those matches.
As suggested in other answers, use of match is redundant in your case and you can go with:
array.map(Number)

You could just map numbers.
var array = ['6.35', '2.72', '11.79', '183.25'],
numbers = array.map(Number);
console.log(numbers);

var num = ['6.35', '2.72', '11.79', '183.25'].map(num => Number(num));
console.log(num);
Number() mdn

Parse the values to float :
console.log(['6.35', '2.72', '11.79', '183.25'].map(i => parseFloat(i)));
If for some reason .map() doesn't work just use a loop :
var array = ['6.35', '2.72', '11.79', '183.25']
var x = 0;
var len = array.length
while(x < len){
array[x] = parseFloat(array[x]);
x++
}
console.log(array)

Map over the array with the Number function, it will handle the conversion:
console.log(['6.35', '2.72', '11.79', '183.25'].map(Number));
If you want commas in your numbers, then you must stick with a string representation.
See this SO answer about a similar problem with ChartJS.

var arr = ["6,35,2,72,11,79,183,25"]
var result=arr.map(Number);
result[]
typeof(result[])

I was having the same problem this is a solution i found
i had
x = "11,1.1,100,100,2,3333,99"
and i wanted
x = [11,1.1,100,100,2,3333,99]
here's my solution
x.toString().replace(/, +/g, ",").split(",").map(Number)

Related

How to parse string value "(20)" to Integer in Javascript?

I'm working with a string "(20)". I need to convert it to an int. I read parseInt is a function which helps me to achieve that, but i don't know how.
Use string slicing and parseInt()
var str = "(20)"
str = str.slice(1, -1) // remove parenthesis
var integer = parseInt(str) // make it an integer
console.log(integer) // 20
One Line version
var integer = parseInt("(20)".slice(1, -1))
The slice method slices the string by the start and end index, start is 1, because that’s the (, end is -1, which means the last one - ), therefore the () will be stripped. Then parseInt() turns it into an integer.
Or use regex so it can work with other cases, credits to #adeithe
var integer = parseInt("(20)".match(/\d+/g))
It will match the digits and make it an integer
Read more:
slicing strings
regex
You can use regex to achieve this
var str = "(20)"
parseInt(str.match(/\d+/g).join())
Easy, use this
var number = parseInt((string).substr(2,3));
You need to extract that number first, you can use the match method and a regex \d wich means "digits". Then you can parse that number
let str = "(20)";
console.log(parseInt(str.match(/\d+/)));
Cleaner version of Hedy's
var str = "(20)";
var str_as_integer = parseInt(str.slice(1, -1))

How to turn all integers in an array into a single number? [duplicate]

How do I join this array to give me expected output in as few steps as possible?
var x = [31,31,3,1]
//expected output: x = 313131;
Use array join method.Join joins the elements of an array into a string, and returns the string. The default separator is comma (,). Here the separator should be an empty string.
var x = [31,31,3,1].join("");
EDIT: To get the result as numeric
const x = +[31,31,3,1].join("");
or
const x = Number([31,31,3,1].join(""));
Javascript join() will give you the expected output as string. If you want it as a number, do this:
var x = [31,31,3,1];
var xAsString = x.join(''); // Results in a string
var xAsNumber = Number(x.join('')); // Results in a number, you can also use +(x.join(''))
I can't think of anything other than
+Function.call.apply(String.prototype.concat, x)
or, if you insist
+''.concat.apply('', x)
In ES6:
+''.concat(...x)
Using reduce:
+x.reduce((a, b) => a + b, '');
Or if you prefer
x.reduce(Function.call.bind(String.prototype.concat), '')
Another idea is to manipulate the array as a string, always a good approach.
+String.prototype.replace.call(x, /,/g, '')
There may be other ways. Perhaps a Google search on "join array javascript" would turn up some obscure function which joins elements of an array.
Your question asks for a number, most of the answers above are going to give you a string. You want something like this.
const number = Number([31,31,3,1].join(""));
Try join() as follows
var x = [31,31,3,1]
var y = x.join('');
alert(y);
Try below.
var x = [31,31,3,1]
var teststring = x.join("");
This will work
var x = [31,31,3,1];
var result = x.join("");

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.
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
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]
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.
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;}));
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

Find the largest number from a string using a regular expression

I have a variable string like:
var myString = "857nano620348splitted3412674relation5305743";
How do I find the largest number from this?
I have tried like the below without any success.
var matches = myString.match(/d+/g);
I'd go for
var myString = "857nano620348splitted3412674relation5305743";
var largest = Math.max.apply(null, myString.match(/\d+/g));
FIDDLE
myString.match(/\d+/g) returns an array of the numbers, and using Math.max.apply(scope, array) returns the largest number in that array.
var numArray = xmr.match(/\d+/g); //this will store all numbers from xmr to numArray.
numArray.sort(function(a,b){return a-b});
var largest = numArray[numArray.length - 1];
You can use the following solution to find the largest number from a string using a regular expression:
var myString ="857nano620348splitted3412674relation5305743";
Math.max(...myString.match(/\d+/g))`

Count the elements in string

I have a string that has comma separated values. How can I count how many elements in the string separated by comma?
e.g following string has 4 elements
string = "1,2,3,4";
myString.split(',').length
var mystring = "1,2,3,4";
var elements = mystring.split(',');
return elements.length;
All of the answers suggesting something equivalent to myString.split(',').length could lead to incorrect results because:
"".split(',').length == 1
An empty string is not what you may want to consider a list of 1 item.
A more intuitive, yet still succinct implementation would be:
myString.split(',').filter((i) => i.length).length
This doesn't consider 0-character strings as elements in the list.
"".split(',').filter((i) => i.length).length
0
"1".split(',').filter((i) => i.length).length
1
"1,2,3".split(',').filter((i) => i.length).length
3
",,,,,".split(',').filter((i) => i.length).length
0
First split it, and then count the items in the array. Like this:
"1,2,3,4".split(/,/).length;
First You need to convert the string to an array using split, then get the length of the array as a count, Desired Code here.
var string = "1,2,3,4";
var desiredCount = string.split(',').length;

Categories