Javascript to convert string to number?

血红的双手。 提交于 2019-12-17 20:08:29

问题


var str = '0.25';

How to convert the above to 0.25?


回答1:


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



回答2:


var num = Number(str);



回答3:


var f = parseFloat(str);




回答4:


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


来源:https://stackoverflow.com/questions/2130454/javascript-to-convert-string-to-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!