如何在 JavaScript 中将字符串转换为整数? [英] How to convert a string to an integer in JavaScript?

查看:42
本文介绍了如何在 JavaScript 中将字符串转换为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

最简单的方法是使用原生的 Number 函数:

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

var x = Number("1000")

如果这对您不起作用,那么有 parseInt一元加parseFloat with floorMath.round 方法.

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

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

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

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

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

如果您是那种在调用 parseInt 时忘记放入基数的类型,您可以使用 parseFloat 并随心所欲地舍入它.这里我使用地板.

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. Here I use floor.

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

有趣的是,Math.round(如 Math.floor)会做一个字符串到数字的转换,所以如果你想要四舍五入的数字(或者如果你在字符串中有一个整数),这是一个很好的方法,也许是我最喜欢的:

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:

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

这篇关于如何在 JavaScript 中将字符串转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆