开发者

Javascript to convert string to number? [duplicate]

This question already has answers here: 开发者_C百科 How to convert a string to an integer in JavaScript (32 answers) Closed 2 years ago.
var str = '0.25';

How to convert the above to 0.25?


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 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


var num = Number(str);


var f = parseFloat(str);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜