与toString相反(36)?

Rai*_*ain 2 javascript numbers type-conversion

var a = (123.456).toString(36) //"3f.gez4w97ry0a18ymf6qadcxr"

现在,如何使用该字符串恢复原始数字?

注意:parseInt(number,36)仅适用于整数.

Doo*_*nob 10

你可以尝试解析整数和浮动部分parseInt,因为parseFloat不支持基数:

function parseFloatInBase(n, radix) {
    var nums = n.split(".")

    // get the part before the decimal point
    var iPart = parseInt(nums[0], radix)
    // get the part after the decimal point
    var fPart = parseInt(nums[1], radix) / Math.pow(radix, nums[1].length)

    return iPart + fPart
}

// this will log 123.456:
console.log(parseFloatInBase("3f.gez4w97ry0a18ymf6qadcxr", 36))
Run Code Online (Sandbox Code Playgroud)

我正在除以radix ^ numLength因为我基本上将小数点移到numLength空格上.你可以像在数学课中那样做,因为你知道除以10会在一个空格上移动小数,因为大多数数学都在基数10中.例如:

123456 / 10 / 10 / 10 = 123.456
Run Code Online (Sandbox Code Playgroud)

这相当于

123456 / (10 * 10 * 10) = 123.456
Run Code Online (Sandbox Code Playgroud)

因此

123456 / (10 ^ 3) = 123.456
Run Code Online (Sandbox Code Playgroud)