采用基数的Javascript函数或方法?

时间:2017-09-13 22:43:28

标签: javascript parsing numbers radix

这些函数将radix作为参数:

  • num.toString(radix);
  • parseInt("123", radix);

是否有任何其他功能或方法需要radix(数字基数), 因为我想使用像parseFloat("1A.B4",radix)这样的东西。

但是因为我不认为它们中有很多,如果你知道的话,请指出它们中的任何一个,非常有用,谢谢。

编辑: 是的parseFloat(“1A.B4”,16)应为26.703125。 如果你看一下,num.toString(radix)它支持从2到36的基数

在Firefox控制台(333.444)中.toString(36)等于“99.fzf9i56mi”

3 个答案:

答案 0 :(得分:1)

@Paulpro's comment推广到函数中,您可以像这样重新定义parseFloat()



parseFloat = function parseFloat (string, radix = 10) {
  if (radix == 10) {
    return this(string)
  }
  
  const [iString, fString = '0'] = string.split('.')
  const iNumber = parseInt(iString, radix)
  const fNumber = parseInt(fString, radix)
  const fLength = Math.max(fNumber.toString(radix).length, fString.length)
  const sign = Infinity / iNumber === Infinity ? 1 : -1
  
  return iNumber + sign * fNumber / radix ** fLength
}.bind(parseFloat)

console.log(parseFloat('1A.B4', 16))
console.log(parseFloat(0.05.toString(16), 16))
console.log(parseFloat('7', 16))
console.log(parseFloat('-0.8', 16))




我不确定这是不是你想要的,但我希望它有所帮助。

答案 1 :(得分:0)

这是我尝试支持基数的parseFloat版本。我试图避免使用Math.pow,因为如果.之后的位很长,我会担心潜在的问题。

function parseFloatRadix(num, radix) {
    var parts = num.trim().split('.'),
        integerStr = parts[0] || '0',
        integer = parseInt(integerStr, radix),
        fractionStr = parts[1] || '0',
        index = fractionStr.length - 1,
        fraction = 0,
        sign = integerStr.charAt(0) === '-' ? -1 : 1;

    for ( ; index >= 0 ; --index) {
        fraction += sign * parseInt(fractionStr.charAt(index), radix);
        fraction /= radix;
    }

    return integer + fraction;
}

[
  12.34,
  12345678,
  0.3,
  0.1 + 0.2, // Note this is not 0.3
  0.01,
  0.001,
  0.0001,
  Math.PI,
  0,
  -1,
  -100,
  -1.5,
  -0.5
].forEach(function(num) {
    var hex = num.toString(16),
        binary = num.toString(2);

    console.log(
        num,
        hex,
        binary,
        parseFloatRadix(hex, 16),
        parseFloatRadix(binary, 2)
    );
});

答案 2 :(得分:0)

  

我想使用类似parseFloat("1A.B4", radix)

好的。尽管parseFloat()中不支持基数,但我们可以像下面这样轻松构建自己的parseFloatRadix()函数:

function parseFloatRadix(num, radix) {
  return parseInt(num.replace('.', ''), radix) /
    Math.pow(radix, (num.split('.')[1] || '').length)
}

This stackowerflow answer提供了更多详细信息。下面的演示代码。

function parseFloatRadix(num, radix) {
  return parseInt(num.replace('.', ''), radix) /
      Math.pow(radix, (num.split('.')[1] || '').length)
}

test('1A.B4', 16, 26.703125);
test('99.fzf9i56mi', 36, 333.444);

function test(num, radix, expected){
  let result = parseFloatRadix(num, radix);
  console.log(num + ' (base ' + radix +') --> ' + result + 
    (result === expected ? ' (OK)' : ' (Expected ' + expected + ')'));
}