Search code examples
javascriptexponentiation

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


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.

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

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.


Solution

  • In ES5 and earlier, use 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:

    let result = 10 ** precision;
    

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