var str = '0.25';
How to convert the above to 0.25?
How to convert a string to a number in JavaScript using the parseInt() function. Another way to convert a string into a number is to use the parseInt() function. This function takes in a string and an optional radix. A radix is a number between 2 and 36 which represents the base in a numeral system.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
The parseInt method parses a value as a string and returns the first integer. A radix parameter specifies the number system to use: 2 = binary, 8 = octal, 10 = decimal, 16 = hexadecimal. If radix is omitted, JavaScript assumes radix 10.
There are several ways to achieve it:
Using the unary plus operator:
var n = +str;
The Number
constructor:
var n = Number(str);
The parseFloat
function:
var n = parseFloat(str);
For your case, just use:
var str = '0.25';
var num = +str;
There are some ways to convert string to number in javascript.
The best way:
var num = +str;
It's simple enough and work with both int and floatnum
will be NaN
if the str
cannot be parsed to a valid number
You also can:
var num = Number(str); //without new. work with both int and float
or
var num = parseInt(str,10); //for integer number
var num = parseFloat(str); //for float number
DO NOT:
var num = new Number(str); //num will be an object. (typeof num == 'object') will be true.
Use parseInt only for special case, for example
var str = "ff";
var num = parseInt(str,16); //255
var str = "0xff";
var num = parseInt(str); //255
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With