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.
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.
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.
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.
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);
Why not:
function precision(x) {
return Math.pow(10, x);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With