我需要将base36字符串解码为两倍.实际的双精度值是0.3128540377812142.现在,当我将其转换为基数36时:
(0.3128540377812142).toString(36);
结果是:
Chrome: 0.b9ginb6s73gd1bfel7npv0wwmi
Firefox: 0.b9ginb6s73e
现在我的问题是:
1)有没有办法为所有浏览器获得相同的base 36结果?
2)如何将它们解码回双精度值?
解决方法:
要将字符串(最大为36)转换为数字,可以使用此方法.
String.prototype.toNumber = function(base) {
var resultNumber = 0;
var inMantissa = false;
var mantissaDivisor;
var currentCharCode;
var digitValue;
if (typeof base === "undefined" || base === "" || base === null) {
base = 10;
}
base = parseInt(base);
if (isNaN(base) || base > 36 || base < 2) {
return NaN;
}
for(var i=0; i<this.length; i++) {
currentCharCode = this.charCodeAt(i);
if (currentCharCode === 46 && !inMantissa) {
// we're at the decimal point
inMantissa = true;
mantissaDivisor = 1;
} else {
if (currentCharCode >= 48 && currentCharCode <= 57) {
// 0-9
digitValue = currentCharCode - 48;
} else if (currentCharCode >= 65 && currentCharCode <= 90) {
// A-Z
digitValue = currentCharCode - 55;
} else if (currentCharCode >= 97 && currentCharCode <= 122) {
// a-z
digitValue = currentCharCode - 87;
} else {
return NaN;
}
if (digitValue > base - 1) {
return NaN;
}
if (inMantissa) {
mantissaDivisor *= base;
resultNumber += digitValue/mantissaDivisor;
} else {
resultNumber = (resultNumber * base) + digitValue;
}
}
}
return resultNumber;
}
这是一个小提琴:http://jsfiddle.net/ugshkp4d/25/
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。