将 10 提高到 javascript 中的幂,有没有比这更好的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6286589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:10:04  来源:igfitidea点击:

Raise 10 to a power in javascript, are there better ways than this

javascriptexponentiation

提问by scubasteve

I have a need to create an integer value to a specific power (that's not the correct term, but basically I need to create 10, 100, 1000, etc.) The "power" will be specified as a function parameter. I came up with a solution but MAN does it feel hacky and wrong. I'd like to learn a better way if there is one, maybe one that isn't string based? Also, eval() is not an option.

我需要创建一个特定幂的整数值(这不是正确的术语,但基本上我需要创建 10、100、1000 等)“幂”将被指定为函数参数。我想出了一个解决方案,但 MAN 是不是感觉很笨拙和错误。如果有一个更好的方法,我想学习一种更好的方法,也许不是基于字符串的方法?此外, eval() 不是一个选项。

Here is what I have at this time:

这是我此时所拥有的:

function makeMultiplierBase(precision)
{
    var numToParse = '1';
    for(var i = 0; i < precision; i++)
    {
        numToParse += '0';
    }

    return parseFloat(numToParse);
}

I also just came up with this non-string based solution, but still seems hacky due to the loop:

我也刚刚提出了这个基于非字符串的解决方案,但由于循环,它仍然看起来很笨拙:

function a(precision)
{
    var tmp = 10;
    for(var i = 1; i < precision; i++)
    {
        tmp *= 10;
    }

    return tmp;
}

BTW, I needed to do this to create a rounding method for working with currency. I had been using var formatted = Math.round(value * 100) / 100

顺便说一句,我需要这样做来创建一个用于处理货币的舍入方法。我一直在使用 var formatted = Math.round(value * 100) / 100

but this code was showing up all over the place and I wanted to have a method take care of the rounding to a specific precision so I created this

但是这段代码到处都是,我想要一种方法来处理到特定精度的舍入,所以我创建了这个

if(!Math.roundToPrecision)
{
    Math.roundToPrecision = function(value, precision)
    {
        Guard.NotNull(value, 'value');

        b = Math.pow(10, precision);
        return Math.round(value * b) / b;
    }  
}

Thought I'd include this here as it's proven to be handy already.

我想我会把它包括在这里,因为它已经被证明已经很方便了。

回答by davin

In ES5 and earlier, use Math.pow:

在 ES5 及更早版本中,使用Math.pow

var result = Math.pow(10, precision);

var precision = 5;
var result = Math.pow(10, precision);
console.log(result);

In ES2016 and later, use the exponentiation operator:

在 ES2016 及更高版本中,使用求幂运算符

let result = 10 ** precision;

let precision = 5;
let result = 10 ** precision;
console.log(result);

回答by RobG

Why not:

为什么不:

function precision(x) {  
  return Math.pow(10, x);
}

回答by Shad

This has the same result as your function, but i still don't understand the application/intention.

这与您的功能具有相同的结果,但我仍然不了解应用程序/意图。

function makeMultiplierBase(precision,base){
    return Math.pow(base||10,precision);
}

回答by loosecannon

if all you need to do is raise 10 to different powers, or any base to any power why not use the built in Math.pow(10,power);unless you have soe specific need to reason to reinvent the wheel

如果您需要做的只是将 10 提高到不同的幂,或者将任何基数提高到任何幂,为什么不使用内置的,Math.pow(10,power);除非您有特定的理由需要重新发明轮子

回答by Andy E

For powers at 1033 and above, Math.pow()may lose precision. For example:

对于 1033 及以上的幂,Math.pow()可能会失去精度。例如:

Math.pow(10, 33);    //-> 1.0000000000000001e+33
Math.pow(10, 34);    //-> 1.0000000000000001e+34
Math.pow(10, 35);    //-> 1e+35
Math.pow(10, 36);    //-> 1e+36
Math.pow(10, 37);    //-> 1.0000000000000001e+37

While not an everyday problem that you may run into in JavaScript, it could be quite troublesome in some situations, particularly with comparison operators. One example is Google's log10Floor()function from the Closure Library:

虽然不是您在 JavaScript 中可能会遇到的日常问题,但在某些情况下可能会非常麻烦,尤其是比较运算符。一个例子是log10Floor()来自 Closure Library 的谷歌函数:

/**
 * Returns the precise value of floor(log10(num)).
 * Simpler implementations didn't work because of floating point rounding
 * errors. For example
 * <ul>
 * <li>Math.floor(Math.log(num) / Math.LN10) is off by one for num == 1e+3.
 * <li>Math.floor(Math.log(num) * Math.LOG10E) is off by one for num == 1e+15.
 * <li>Math.floor(Math.log10(num)) is off by one for num == 1e+15 - 1.
 * </ul>
 * @param {number} num A floating point number.
 * @return {number} Its logarithm to base 10 rounded down to the nearest
 *     integer if num > 0. -Infinity if num == 0. NaN if num < 0.
 */
goog.math.log10Floor = function(num) {
  if (num > 0) {
    var x = Math.round(Math.log(num) * Math.LOG10E);
    return x - (Math.pow(10, x) > num);
  }
  return num == 0 ? -Infinity : NaN;
};

If you pass a power of 10 above 1033, this function could return an incorrect result because Math.pow(10, 33) > 1e33evaluates to true. The way I worked around this is to use Number coercion, concatenating the exponent to '1e':

如果您传递 1033 以上的 10 的幂,则此函数可能会返回不正确的结果,因为Math.pow(10, 33) > 1e33计算结果为true。我解决这个问题的方法是使用数字强制,将指数连接到“1e”:

+'1e33'    //-> 1e+33
+'1e34'    //-> 1e+34
+'1e35'    //-> 1e+35
+'1e36'    //-> 1e+36
+'1e37'    //-> 1e+37

And, fixing the log10Floor()function:

并且,修复log10Floor()功能:

goog.math.log10Floor = function(num) {
  if (num > 0) {
    var x = Math.round(Math.log(num) * Math.LOG10E);
    return x - (+('1e' + x) > num);
  }
  return num == 0 ? -Infinity : NaN;
};

Note: The bug in closure library has since been fixed.

注意:闭包库中的错误已被修复

回答by ninjaas

I just stumbled on something while going through https://github.com/aecostas/huffman. The compiled code(js) has a line

我只是在浏览https://github.com/aecostas/huffman 时偶然发现了一些东西。编译后的代码(js)有一行

alphabet_next = sorted.slice(0, +(sorted.length - 1 - groupsize) + 1 || 9e9);

If you try to evaluate 9e9 (on the node and browser console) it gives you 9000000000 which is "9*10^9".Based on that you could simply do the below to get the 10th power. var n = 2; eval("1e"+n); //outputs 100

如果您尝试评估 9e9(在节点和浏览器控制台上),它会为您提供 9000000000,即“9*10^9”。基于此,您可以简单地执行以下操作以获得 10 次方。 var n = 2; eval("1e"+n); //outputs 100

EDIT: More on exponential notation from http://www.2ality.com/2012/03/displaying-numbers.html.

编辑:更多关于指数表示法来自 http://www.2ality.com/2012/03/displaying-numbers.html

There are two decimal notations used by JavaScript: Fixed notation [ "+" | "-" ] digit+ [ "." digit+ ] and exponential notation [ "+" | "-" ] digit [ "." digit+ ] "e" [ "+" | "-" ] digit+ An example of exponential notation is -1.37e+2. For output, there is always exactly one digit before the point, for input you can use more than one digit. Exponential notation is interpreted as follows: Given a number in exponential notation: significand e exponent. The value of that number is significand× 10exponent. Hence, -1.37e+2 represents the number ?137.

JavaScript 使用两种十进制表示法: 固定表示法 [ "+" | "-" ] 数字+ [ "." digit+ ] 和指数符号 [ "+" | “-“ ] 数字 [ ”。” 数字+ ] "e" [ "+" | "-" ] digit+ 指数表示法的一个例子是 -1.37e+2。对于输出,点前总是正好有一位,对于输入,您可以使用多于一位。指数表示法解释如下: 给定一个指数表示法的数字: 有效数 e 指数。该数字的值是有效数 × 10指数。因此,-1.37e+2 代表数字?137。

回答by user207421

Use a lookup table. But if this is for rounding currency amounts, you should be using BigDecimal instead of the entire schemozzle.

使用查找表。但如果这是为了四舍五入的货币金额,您应该使用 BigDecimal 而不是整个 schemozzle。