Steve K - 1 year ago 85

Javascript Question

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.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**