javascript - 将表示任意基数的字符串转换为数字

标签 javascript jquery ajax html

我需要将 base36 字符串解码为 double。实际 double 值为 0.3128540377812142。现在,当我将它转换为 base 36 时:

(0.3128540377812142).toString(36);

结果是:

Chrome: 0.b9ginb6s73gd1bfel7npv0wwmi
Firefox: 0.b9ginb6s73e

现在我的问题是:

1) 有什么方法可以让所有浏览器都获得相同的 base 36 结果吗?

2) 如何将它们解码回 double 值?

最佳答案

要将字符串(最多 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;
}

这是一个 fiddle :http://jsfiddle.net/ugshkp4d/25/

关于javascript - 将表示任意基数的字符串转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33023868/

相关文章:

javascript - DOM 元素添加到 DOM 树后是否立即可用?

在 Django 问题中使用 ajax 的 javascript-POST 请求

javascript - 为什么这个 jquery 动画没有像预期的那样旋转?

javascript - Stringify 返回 Object 对象?

Javascript 在文本上暂停和恢复过渡动画

javascript - Primefaces 条形图禁用所有系列

javascript - 使用 jQuery Flot 通过 AJAX 接收数据

javascript - 在选择过滤器更改时自动提交 AJAX 搜索表单

javascript - 猫头鹰旋转木马无法自动播放

javascript - Yii - 将 onclick 事件与 CLinkPager 与每个寻呼机链接绑定(bind)