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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: