freeradik
freeradik

Reputation: 7

Which javascript function can be used to covert an array of characters into a number?

There are a few Javascript functions available to convert anything into its equivalent number. Number() operates on an Object, valueOf(), parseFloat, parseInt() are also available.

I have an array which stores numbers 0-9 and decimal point, the elements of the array taken together represents a number. What is the best way to convert this array into a number, whole or fractional?

EDIT: Apologies if I were not clear before. The array, holding the 0-9 characters and possibly a decimal point, could represent either a whole number(without the decimal obviously) or a fractional number. So please suggest something that works for both cases. Thanks.

Upvotes: 0

Views: 78

Answers (3)

andre mcgruder
andre mcgruder

Reputation: 1520

You could use the split property of the string. It splits all the characters into an zero based array.

var charSplits = "this is getting split.";

var splitArr = charSplits.split();

Console.log(splitArr);

// this returns i 
Console.log(splitArr[2]);

Upvotes: 0

Matt Way
Matt Way

Reputation: 33189

What is the best way to convert this array into a number, whole or fractional?

Firstly to combine your array elements you should use Array.join().

You will then have a concatenated variable of your values and decimal. To convert this to a whole number, use parseInt(), and to a floating point number use parseFloat(). You can use the unary + operator (which acts similarly to parseFloat), however in my opinion it is not the best choice semantically here, as you seem to want a specific type of number returned.

Example:

var arr = ['1','.','9','1'];
var concat = arr.join();
var whole = parseInt(concat);
var floating = parseFloat(concat);

Also, parseInt will trim the decimal portion of your number, so if you need rounding you can use:

var rounded = Math.round(parseFloat(concat));

Upvotes: 0

11thdimension
11thdimension

Reputation: 10653

Try this

var a = [1,2,3,".",2,3];
var num = +a.join("");

Upvotes: 4

Related Questions