Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to convert string to number? [duplicate]

var str = '0.25';

How to convert the above to 0.25?

like image 946
user198729 Avatar asked Jan 25 '10 05:01

user198729


People also ask

How do I convert a string to a number in JavaScript?

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.

How do I convert a string to an array in JavaScript?

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.

How do I use parseInt in JavaScript?

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.


2 Answers

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);
like image 93
Christian C. Salvadó Avatar answered Oct 28 '22 07:10

Christian C. Salvadó


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 float
num 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
like image 20
cuixiping Avatar answered Oct 28 '22 05:10

cuixiping