Extracting the exponent and mantissa of a Javascript Number

后端 未结 8 617
执笔经年
执笔经年 2020-12-03 03:03

Is there a reasonably fast way to extract the exponent and mantissa from a Number in Javascript?

AFAIK there\'s no way to get at the bits behind a Number in Javascri

相关标签:
8条回答
  • 2020-12-03 04:04

    While I liked the accepted solution, using it to work on arbitrary base re-introduced all of the errors caused by Math.log and Math.pow. Here is a small implementation for any base: x = mantisse * b^exponent

    function numberParts(x, b) {
      var exp = 0
      var sgn = 0
      if (x === 0) return { sign: 0, mantissa: 0, exponent: 0 }
      if (x<0) sgn=1, x=-x
      while (x>b) x/=b, exp++
      while (x<1) x*=b, exp--
      return { sign: sgn, mantissa: x, exponent: exp }
    }
    

    The NaN and Infinite cases can easily be added. If the distinction between +0 and -0 is important:

    if (1/x === Infinity) return { sign: 0, mantissa: 0, exponent: 0 }
    if (1/x === -Infinity) return { sign: 1, mantissa: 0, exponent: 0 }
    
    0 讨论(0)
  • 2020-12-03 04:09

    What about following to get the exponent?:

    let exp = String(number.toExponential());
    exp = Number(exp.substr(exp.lastIndexOf('e')+1));
    

    1000 will result in exp = 3

    0 讨论(0)
提交回复
热议问题