Javascript 整数比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11306071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Integer Comparison
提问by User
I need to compare two Integers which could exceed Integer range limit. How do I get this in javascript. Initially, I get the value as String, do a parseInt and compare them.
我需要比较两个可能超过整数范围限制的整数。我如何在 javascript 中得到这个。最初,我将值作为字符串,执行 parseInt 并比较它们。
var test = document.getElementById("test").value;
var actual = document.getElementById("actual").value;
if ( parseInt(test) == parseInt(actual)){
return false;
}
Any options to use long ? Also, which is best to use parseInt or valueOf ??
任何使用 long 的选项?另外,哪个最好使用 parseInt 或 valueOf ??
Any suggestions appreciated,
任何建议表示赞赏,
Thanks
谢谢
回答by nhahtdh
Leave them in String and compare (after you have cleaned up the string of leading and trailing spaces, and other characters that you consider safe to remove without changing the meaning of the number).
将它们留在 String 中并进行比较(在您清理了前导和尾随空格的字符串以及您认为可以安全删除而不改变数字含义的其他字符之后)。
The numbers in Javascript can go up to 53-bit precision. Check whether your number is within range.
Javascript 中的数字可以达到 53 位精度。检查您的号码是否在范围内。
Since the input is expected to be integer, you can be strict and only allow the input to only match the regex:
由于输入应该是整数,你可以严格并且只允许输入只匹配正则表达式:
/\s*0*([1-9]\d*|0)\s*/
(Arbitrary leading spaces, arbitrary number of leading 0's, sequence of meaningful digits or single 0, arbitrary trailing spaces)
(任意前导空格、任意数量的前导 0、有意义的数字序列或单个 0、任意尾随空格)
The number can be extract from the first capturing group.
该数字可以从第一个捕获组中提取。
回答by xdazz
You'd better to assign the radix. Ex. parseInt('08')
will give 0
not 8
.
你最好分配基数。前任。parseInt('08')
将给予0
不8
。
if (parseInt(test, 10) === parseInt(actual, 10)) {
回答by jfriend00
Assuming integers and that you've already validated for non-numeric characters that you don't want to be part of the comparison, you can clean up some leading/trailing stuff and then just compare lengths and if lengths are equal, then do a plain ascii comparison and this will work for any arbitrary length of number:
假设整数并且您已经验证了您不想成为比较一部分的非数字字符,您可以清理一些前导/尾随内容,然后只比较长度,如果长度相等,则执行纯 ascii 比较,这适用于任意长度的数字:
function mTrim(val) {
var temp = val.replace(/^[\s0]+/, "").replace(/\s+$/, "");
if (!temp) {
temp = "0";
}
return(temp);
}
var test = mTrim(document.getElementById("test").value);
var actual = mTrim(document.getElementById("actual").value);
if (test.length > actual.length) {
// test is greater than actual
} else if (test.length < actual.length) {
// test is less than actual
} else {
// do a plain ascii comparison of test and actual
if (test == actual) {
// values are the same
} else if (test > ascii) {
// test is greater than actual
} else {
// test is less than actual
}
}