Nos*_*dna 2047
最简单的方法是使用本机Number函数:
var x = Number("1000")
Run Code Online (Sandbox Code Playgroud)
如果这对你不起作用,那么有parseInt,unary plus,parseFloat with floor和Math.round方法.
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])
Run Code Online (Sandbox Code Playgroud)
如果您的字符串已经是整数形式,则为unary plus:
var x = +"1000";
Run Code Online (Sandbox Code Playgroud)
如果你的字符串是或者可能是一个浮点数,你想要一个整数:
var x = Math.floor("1000.01"); //floor automatically converts string to number
Run Code Online (Sandbox Code Playgroud)
或者,如果您要多次使用Math.floor:
var floor = Math.floor;
var x = floor("1000.01");
Run Code Online (Sandbox Code Playgroud)
如果您是在调用parseInt时忘记放入基数的类型,则可以使用parseFloat并根据需要对其进行舍入.我在这里用地板.
var floor = Math.floor;
var x = floor(parseFloat("1000.01"));
Run Code Online (Sandbox Code Playgroud)
有趣的是,Math.round(如Math.floor)将进行字符串到数字的转换,所以如果你想要数字舍入(或者如果字符串中有一个整数),这是一个很好的方式,也许是我的最爱:
var round = Math.round;
var x = round("1000"); //equivalent to round("1000",0)
Run Code Online (Sandbox Code Playgroud)
Zan*_*oni 217
试试parseInt函数:
var number = parseInt("10");
Run Code Online (Sandbox Code Playgroud)
但有一个问题.如果您尝试使用parseInt函数转换"010",它会检测为八进制数,并返回数字8.因此,您需要指定一个基数(从2到36).在这种情况下,基地10.
parseInt(string, radix)
Run Code Online (Sandbox Code Playgroud)
例:
var result = parseInt("010", 10) == 10; // Returns true
var result = parseInt("010") == 10; // Returns false
Run Code Online (Sandbox Code Playgroud)
请注意,parseInt在解析任何有效内容后忽略错误数据.
这个guid将解析为51:
var result = parseInt('51e3daf6-b521-446a-9f5b-a1bb4d8bac36', 10) == 51; // Returns true
Run Code Online (Sandbox Code Playgroud)
kyb*_*kos 120
在javascript中将字符串转换为数字有两种主要方法.一种方法是解析它,另一种方法是将其类型更改为数字.其他答案中的所有技巧(例如一元加)都涉及隐含地将字符串的类型强制转换为数字.您也可以使用Number函数显式执行相同的操作.
解析
var parsed = parseInt("97", 10);
Run Code Online (Sandbox Code Playgroud)
parseInt和parseFloat是用于将字符串解析为数字的两个函数.解析会在遇到无法识别的字符时静默停止,这对于解析像"92px"这样的字符串很有用,但它也有点危险,因为它不会在输入错误时给你任何错误,而是你除非字符串以数字开头,否则将返回NaN.字符串开头的空格将被忽略.这是一个例子,它做了一些不同于你想要的东西,并没有表明出现任何问题:
var widgetsSold = parseInt("97,800", 10); // widgetsSold is now 97
Run Code Online (Sandbox Code Playgroud)
总是将基数指定为第二个参数是一种好习惯.在较旧的浏览器中,如果字符串以0开头,如果未指定基数,则会将其解释为八进制,这会让很多人感到意外.如果没有指定基数,则通过使字符串以0x开头来触发十六进制的行为,例如0xff.标准实际上是用ecmascript 5改变的,所以如果没有指定基数,那么现代浏览器不会再触发八进制.parseInt将基数理解为基数36,在这种情况下,大写和小写字母都被视为等价.
将字符串的类型更改为数字
上面提到的所有其他不使用parseInt的技巧都涉及隐式地将字符串强制转换为数字.我更愿意明确地这样做,
var cast = Number("97");
Run Code Online (Sandbox Code Playgroud)
这与解析方法有不同的行为(尽管它仍然忽略空格).它更严格:如果它不理解整个字符串而不是它返回NaN,那么你不能将它用于像字符串这样的字符串97px.由于您需要原始数字而不是数字包装器对象,因此请确保不要放在new数字函数前面.
显然,转换为Number会给出一个可能是float而不是整数的值,所以如果你想要一个整数,你需要修改它.有几种方法可以做到这一点:
var rounded = Math.floor(Number("97.654")); // other options are Math.ceil, Math.round
var fixed = Number("97.654").toFixed(0); // rounded rather than truncated
var bitwised = Number("97.654")|0; // do not use for large numbers
Run Code Online (Sandbox Code Playgroud)
任何按位运算符(这里我做了一个按位或,但你也可以做一个双重否定,如在前面的回答或一个位移)将把值转换为32位整数,其中大多数将转换为有符号整数.请注意,这不希望您想要大整数.如果整数不能用32位表示,它将换行.
~~"3000000000.654" === -1294967296
// This is the same as
Number("3000000000.654")|0
"3000000000.654" >>> 0 === 3000000000 // unsigned right shift gives you an extra bit
"300000000000.654" >>> 0 === 3647256576 // but still fails with larger numbers
Run Code Online (Sandbox Code Playgroud)
要使用更大的数字,您应该使用舍入方法
Math.floor("3000000000.654") === 3000000000
// This is the same as
Math.floor(Number("3000000000.654"))
Run Code Online (Sandbox Code Playgroud)
请记住,所有的这些方法的理解指数形式,所以2e2是200不是NaN的.此外,Number理解"Infinity",而解析方法则不理解.
习惯
这些方法中的任何一种都不可能完全符合您的要求.例如,通常我希望在解析失败时抛出错误,并且我不需要支持Infinity,指数或前导空格.根据您的用例,有时编写自定义转换函数是有意义的.
始终检查Number或其中一个解析方法的输出是否是您期望的数字.您几乎肯定会想要isNaN确保该数字不是NaN(通常是您发现解析失败的唯一方法).
小智 50
ParseInt()和+是不同的
parseInt("10.3456") // returns 10
+"10.3456" // returns 10.3456
Run Code Online (Sandbox Code Playgroud)
dav*_*dav 36
虽然这是一个古老的问题,但也许这对某人有帮助.
我用这种方式将字符串转换为int数
var str = "25"; // string
var number = str*1; // number
Run Code Online (Sandbox Code Playgroud)
因此,当乘以1时,该值不会改变,但js会自动返回一个数字.
但是如下所示,如果你确定它str是一个数字(或者可以表示为数字),则应该使用它,否则它将返回NaN - 而不是数字.
你可以创建简单的功能,例如
function toNumber(str) {
return str*1;
}
Run Code Online (Sandbox Code Playgroud)

Sol*_*ogi 33
试试parseInt.
var number = parseInt("10", 10); //number will have value of 10.
Run Code Online (Sandbox Code Playgroud)
Kam*_*ski 31
var x = "1000"*1;
Run Code Online (Sandbox Code Playgroud)
这里有一点速度比较(仅限Mac Os)...... :)
对于chrome'plus'和'mul'来说最快(> 700,000,00 op/sec),'Math.floor'是最慢的.对于Firefox'plus'是最慢的(!)'mul'是最快的(> 900,000,000 op/sec).在Safari中,'parseInt'很精巧,'number'是最慢的(但是resulats非常相似,> 13,000,000 <31,000,000).因此,用于将字符串转换为int的Safari比其他浏览器慢10倍.所以获胜者是' mul ':)
您可以通过此链接https://jsperf.com/casttonumber在浏览器上运行它
更新
我也测试var x = ~~"1000";- 在Chrome和Safari上稍慢var x = "1000"*1(<1%),在Firefox上稍微快一点(<1%).
Ian*_*Ooi 26
我在这里发错了答案,抱歉.固定.
这是一个老问题,但我喜欢这个诀窍:
~~"2.123"; //2
~~"5"; //5
Run Code Online (Sandbox Code Playgroud)
双位按位负数会在小数点后丢弃任何内容并将其转换为数字格式.我被告知它比调用函数和诸如此类的东西要快一些,但我并不完全相信.
编辑:另一种方法我刚才看到这里(绕的javascript >>>运营商,这是一个问题零填充右移),这表明由0与该运营商转移了一批数字转换为UINT32这是很好的,如果你也希望它没有签名.同样,这会转换为无符号整数,如果使用带符号的数字,可能会导致奇怪的行为.
"-2.123" >>> 0; // 4294967294
"2.123" >>> 0; // 2
"-5" >>> 0; // 4294967291
"5" >>> 0; // 5
Run Code Online (Sandbox Code Playgroud)
Tec*_*nav 20
在 JavaScript 中,您可以执行以下操作:
解析整数
parseInt("10.5") // Returns 10
Run Code Online (Sandbox Code Playgroud)
乘以 1
var s = "10";
s = s*1; // Returns 10
Run Code Online (Sandbox Code Playgroud)
使用一元运算符 (+)
var s = "10";
s = +s; // Returns 10
Run Code Online (Sandbox Code Playgroud)
使用按位运算符
(注意:它在 后开始损坏2140000000。示例~~"2150000000" = -2144967296:)
var s = "10.5";
s = ~~s; // Returns 10
Run Code Online (Sandbox Code Playgroud)
使用 Math.floor() 或 Math.ceil()
var s = "10";
s = Math.floor(s) || Math.ceil(s); // Returns 10
Run Code Online (Sandbox Code Playgroud)
小智 18
请注意,如果您使用parseInt以科学计数法转换浮点数!例如:
parseInt("5.6e-14")
Run Code Online (Sandbox Code Playgroud)
会导致
5
Run Code Online (Sandbox Code Playgroud)
代替
0
Run Code Online (Sandbox Code Playgroud)
Dev*_*ner 16
要将String转换为Integer,我建议使用parseFloat和NOT parseInt.原因如下:
使用parseFloat:
parseFloat('2.34cms') //Output: 2.34
parseFloat('12.5') //Output: 12.5
parseFloat('012.3') //Output: 12.3
Run Code Online (Sandbox Code Playgroud)
使用parseInt:
parseInt('2.34cms') //Output: 2
parseInt('12.5') //Output: 12
parseInt('012.3') //Output: 12
Run Code Online (Sandbox Code Playgroud)
因此,如果您注意到parseInt丢弃小数点后的值,而parseFloat允许您使用浮点数,因此如果您想保留小数点后的值,则更合适.当且仅当您确定需要整数值时才使用parseInt.
Hen*_*sen 15
另外作为旁注:Mootools具有函数toInt(),用于任何本地字符串(或浮点(或整数)).
"2".toInt() // 2
"2px".toInt() // 2
2.toInt() // 2
Run Code Online (Sandbox Code Playgroud)
zee*_*han 14
请看下面的例子.这将有助于消除您的疑虑
Example Result
parseInt("4") 4
parseInt("5aaa") 5
parseInt("4.33333") 4
parseInt("aaa"); NaN (means "Not a Number")
Run Code Online (Sandbox Code Playgroud)
通过使用parseint函数它只会给出整数存在的op而不是字符串
Rev*_* V. 13
我们可以使用+(stringOfNumber)而不是使用parseInt(stringOfNumber)
例如:+("21")返回21的int类似于parseInt("21").
我们可以使用这个一元"+"运算符来解析浮点数...
zan*_*ngw 10
尝试str - 0转换string为number.
> str = '0'
> str - 0
0
> str = '123'
> str - 0
123
> str = '-12'
> str - 0
-12
> str = 'asdf'
> str - 0
NaN
> str = '12.34'
> str - 0
12.34
Run Code Online (Sandbox Code Playgroud)
以下是两个链接,用于比较将字符串转换为int的几种方法的性能
https://jsperf.com/number-vs-parseint-vs-plus
http://phrogz.net/js/string_to_number.html
Ali*_*eza 10
JavaScript中有很多种方法可以将字符串转换为数字值...所有简单方便,选择适合您的方式:
var num = Number("999.5"); //999.5
var num = parseInt("999.5", 10); //999
var num = parseFloat("999.5"); //999.5
var num = +"999.5"; //999.5
Run Code Online (Sandbox Code Playgroud)
任何Math操作也会将它们转换为数字,例如......
var num = "999.5" / 1; //999.5
var num = "999.5" * 1; //999.5
var num = "999.5" - 1 + 1; //999.5
var num = "999.5" - 0; //999.5
var num = Math.floor("999.5"); //999
var num = ~~"999.5"; //999
Run Code Online (Sandbox Code Playgroud)
我更喜欢使用+sign,这是在JavaScript中将字符串转换为数字的优雅方式.
JS-*_*nan 10
+numStr与其他产品相比,易于使用且性能更好console.log(+'123.45') // => 123.45
Run Code Online (Sandbox Code Playgroud)
parseInt(numStr)对于整数parseFloat(numStr)对于整数和小数console.log(parseInt('123.456')) // => 123
console.log(parseFloat('123')) // => 123
Run Code Online (Sandbox Code Playgroud)
数学函数,例如round(numStr), floor(numStr), ceil(numStr)整数
Number(numStr)对于整数和小数
console.log(Math.floor('123')) // => 123
console.log(Math.round('123.456')) // => 123
console.log(Math.ceil('123.454')) // => 124
console.log(Number('123.123')) // => 123.123
Run Code Online (Sandbox Code Playgroud)
所有基本一元运算符 、+numStr、numStr-0、1*numStr、numStr*1和numStr/1
全部支持整数和小数
需谨慎numStr+0。它返回一个字符串。
console.log(+'123') // => 123
console.log('002'-0) // => 2
console.log(1*'5') // => 5
console.log('7.7'*1) // => 7.7
console.log(3.3/1) // =>3.3
console.log('123.123'+0, typeof ('123.123' + 0)) // => 123.1230 string
Run Code Online (Sandbox Code Playgroud)
~~numStr或左移 0,numStr<<0console.log(~~'123') // => 123
console.log('0123'<<0) // => 123
console.log(~~'123.123') // => 123
console.log('123.123'<<0) // => 123
Run Code Online (Sandbox Code Playgroud)
// Parsing
console.log(parseInt('123.456')) // => 123
console.log(parseFloat('123')) // => 123
// Function
console.log(Math.floor('123')) // => 123
console.log(Math.round('123.456')) // => 123
console.log(Math.ceil('123.454')) // => 124
console.log(Number('123.123')) // => 123.123
// Unary
console.log(+'123') // => 123
console.log('002'-0) // => 2
console.log(1*'5') // => 5
console.log('7.7'*1) // => 7.7
console.log(3.3/1) // => 3.3
console.log('123.123'+0, typeof ('123.123'+0)) // => 123.1230 string
// Bitwise
console.log(~~'123') // => 123
console.log('0123'<<0) // => 123
console.log(~~'123.123') // => 123
console.log('123.123'<<0) // => 123Run Code Online (Sandbox Code Playgroud)
在我看来,没有答案涵盖所有边缘情况,因为解析浮点应该导致错误.
function parseInteger(value) {
if(value === '') return NaN;
const number = Number(value);
return Number.isInteger(number) ? number : NaN;
}
Run Code Online (Sandbox Code Playgroud)
parseInteger("4") // 4
parseInteger("5aaa") // NaN
parseInteger("4.33333") // NaN
parseInteger("aaa"); // NaN
Run Code Online (Sandbox Code Playgroud)
这是最简单的解决方案
let myNumber = "123" | 0;
Run Code Online (Sandbox Code Playgroud)
更简单的解决方案
let myNumber = +"123";
Run Code Online (Sandbox Code Playgroud)
最简单的方法是+像这样使用
const strTen = "10"
const numTen = +strTen // string to number conversion
console.log(typeof strTen) // string
console.log(typeof numTen) // number
Run Code Online (Sandbox Code Playgroud)
谷歌给了我这个答案,所以......
我实际上需要将一个字符串"保存"为一个整数,用于C和JavaScript之间的绑定,所以我将字符串转换为整数值:
/*
Examples:
int2str( str2int("test") ) == "test" // true
int2str( str2int("t€st") ) // "t¬st", because "€".charCodeAt(0) is 8364, will be AND'ed with 0xff
Limitations:
max 4 chars, so it fits into an integer
*/
function str2int(the_str) {
var ret = 0;
var len = the_str.length;
if (len >= 1) ret += (the_str.charCodeAt(0) & 0xff) << 0;
if (len >= 2) ret += (the_str.charCodeAt(1) & 0xff) << 8;
if (len >= 3) ret += (the_str.charCodeAt(2) & 0xff) << 16;
if (len >= 4) ret += (the_str.charCodeAt(3) & 0xff) << 24;
return ret;
}
function int2str(the_int) {
var tmp = [
(the_int & 0x000000ff) >> 0,
(the_int & 0x0000ff00) >> 8,
(the_int & 0x00ff0000) >> 16,
(the_int & 0xff000000) >> 24
];
var ret = "";
for (var i=0; i<4; i++) {
if (tmp[i] == 0)
break;
ret += String.fromCharCode(tmp[i]);
}
return ret;
}
Run Code Online (Sandbox Code Playgroud)
function parseIntSmarter(str) {
// ParseInt is bad because it returns 22 for "22thisendsintext"
// Number() is returns NaN if it ends in non-numbers, but it returns 0 for empty or whitespace strings.
return isNaN(Number(str)) ? NaN : parseInt(str, 10);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1317942 次 |
| 最近记录: |