最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Opposite of toString(36)? - Stack Overflow

programmeradmin3浏览0评论

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

Now, how do I revert back to the original number using that string?

Note: parseInt(number,36) only works for integers.

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

Now, how do I revert back to the original number using that string?

Note: parseInt(number,36) only works for integers.

Share Improve this question edited Jan 8, 2014 at 2:57 hexacyanide 91.9k31 gold badges166 silver badges162 bronze badges asked Jan 8, 2014 at 2:37 RainingChainRainingChain 7,79210 gold badges38 silver badges69 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

You could try parsing the integer and float parts separately with parseInt, as parseFloat does not support a radix:

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))

I am dividing by radix ^ numLength because I am basically moving the decimal point over numLength spaces. You would do this just like in math class, because as you know dividing by 10 moves the decimal over one space, because most math is in base 10. Example:

123456 / 10 / 10 / 10 = 123.456

This is equivalent to

123456 / (10 * 10 * 10) = 123.456

And therefore

123456 / (10 ^ 3) = 123.456
发布评论

评论列表(0)

  1. 暂无评论