Convert negative number in string to negative decimal in JavaScript

The parseInt function can be used to parse strings to integers and uses this format: parseInt(string, radix);

Ex: parseInt("-10.465", 10); returns -10

To parse floating point numbers, you use parseFloat, formatted like parseFloat(string)

Ex: parseFloat("-10.465"); returns -10.465


Simply pass it to the Number function:

var num = Number(str);

Here are two simple ways to do this if the variable str = "-10.123":

#1

str = str*1;

#2

str = Number(str);

Both ways now contain a JavaScript number primitive now. Hope this helps!

Tags:

Javascript