Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 690
scubasteve Avatar asked Jun 08 '11 23:06

scubasteve


People also ask

How do you code exponents in JavaScript?

The exponentiation operator (**) can also be used to get the exponent power of a number. It returns a number which is the result of raising the first operand to the power of the second operand. It is the same as the Math.

How do you raise a number to the power of 10?

Thus, shown in long form, a power of 10 is the number 1 followed by n zeros, where n is the exponent and is greater than 0; for example, 106 is written 1,000,000. When n is less than 0, the power of 10 is the number 1 n places after the decimal point; for example, 10−2 is written 0.01.

How do you write squared in JavaScript?

pow() The best way to square a number is to use the Math. pow() function. This function is used to take a number and raise it to a power.


2 Answers

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);
like image 53
davin Avatar answered Oct 10 '22 19:10

davin


Why not:

function precision(x) {  
  return Math.pow(10, x);
}
like image 34
RobG Avatar answered Oct 10 '22 18:10

RobG