April 12, 2011

JavaScript fixed length double

Posted in Uncategorized tagged , , , at 5:31 pm by tetontech

For those of you who are using monetary or other fixed length values in your app here is a little function to help you out.  It accepts any numeric or string values and produces a string that can be used for further calculation as a number or displayed.  If the number is shorter than the precision indicated the function will pad it with zero characters until it is the correct length.

 

Enjoy.

 

Call it like this:  var fixedLengthFloat = toFixed(3.2, 10);

 

The function:

 

function toFixed(value, precision) {

if(isNaN(value)){

value = 0;

}

if(precision < 0){

precision = 0;

}

var power = Math.pow(10, precision || 0);

var result = String(Math.round(value * power) / power);

if(precision > 0){

if(result.indexOf(‘.’) == -1){

result += ‘.’;

for(var i = 0; i < precision; i++){

result += ‘0’;

}

}

else{

var decimalPortion = result.substring(result.indexOf(‘.’)+1, result.length);

var placesMissing = precision – decimalPortion.length;

for(var i = 0; i < placesMissing; i++){

result += ‘0’;

}

}

}

return result;

}

Advertisements

%d bloggers like this: