我有2个大变量,我需要比较如下:
var a = 15000000000000000000000001 // integer
var b = "15000000000000000000000000" // string
在我的所有测试比较中得到错误的结果。 例如:
将var b转换为整数
var a = 15000000000000000000000001 var b = 15000000000000000000000000 a > b // return false and is wrong
将var a转换为字符串
var a = "1500000000000000000000001" var b = "15000000000000000000000000" a > b // return true and is wrong
我的解决方案:
function compareCheck(a,b){
if (a.length > b.length) {
return true;
}
else if (a.length == b.length) {
if (a.localeCompare(b) > 0) {
return true
}
else return false;
}
else return false;
}
var a = "15000000000000000000000001"
var b = "15000000000000000000000000"
compareCheck(a,b) // return true and is correct
var a = "1500000000000000000000001"
var b = "15000000000000000000000000"
compareCheck(a,b) // return false and is correct
我的问题是,找到的解决方案是正确的,还是将来会出现问题?
答案 0 :(得分:1)
我认为标准做法是从另一个数字中减去一个数字并将其与epsilon值进行比较。