Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

javascript - 将字符串转换为整数?(Convert a string to an integer?)

如何在JavaScript中将字符串转换为整数?

  ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The simplest way would be to use the native Number function:

(最简单的方法是使用本机Number函数:)

var x = Number("1000")

If that doesn't work for you, then there are the parseInt , unary plus , parseFloat with floor , and Math.round methods.

(如果这对您不起作用,则有parseInt一元plus带有floor的parseFloatMath.round方法。)

parseInt:

(parseInt:)

var x = parseInt("1000", 10); // you want to use radix 10
    // so you get a decimal number even with a leading 0 and an old browser ([IE8, Firefox 20, Chrome 22 and older][1])

unary plus if your string is already in the form of an integer:

(一元加号,如果您的字符串已经是整数形式:)

var x = +"1000";

if your string is or might be a float and you want an integer:

(如果您的字符串是浮点数或可能是浮点数,并且您想要一个整数:)

var x = Math.floor("1000.01"); //floor automatically converts string to number

or, if you're going to be using Math.floor several times:

(或者,如果您要多次使用Math.floor:)

var floor = Math.floor;
var x = floor("1000.01");

If you're the type who forgets to put the radix in when you call parseInt, you can use parseFloat and round it however you like.

(如果您是在调用parseInt时忘记将基数放入的类型,则可以使用parseFloat并根据需要将其四舍五入。)

Here I use floor.

(在这里我用地板。)

var floor = Math.floor;
var x = floor(parseFloat("1000.01"));

Interestingly, Math.round (like Math.floor) will do a string to number conversion, so if you want the number rounded (or if you have an integer in the string), this is a great way, maybe my favorite:

(有趣的是,Math.round(例如Math.floor)将进行字符串到数字的转换,因此,如果您想将数字四舍五入(或者如果字符串中有整数),这是一个很好的方法,也许是我的最爱:)

var round = Math.round;
var x = round("1000"); //equivalent to round("1000",0)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...