Javascripts > Misc Javascripts > Format Number
Script Title: Format Number
Description: This function formats a numeric value passed in to it with specified number of decimal values. Numeric value will not be rounded.
Example: Available
Copy the following code into your <HEAD></HEAD> tags.<script language="JavaScript"> function format_number(pnumber,decimals){ if (isNaN(pnumber)) { return 0}; if (pnumber=='') { return 0}; var snum = new String(pnumber); var sec = snum.split('.'); var whole = parseFloat(sec[0]); var result = ''; if(sec.length > 1){ var dec = new String(sec[1]); dec = String(parseFloat(sec[1])/Math.pow(10,(dec.length - decimals))); dec = String(whole + Math.round(parseFloat(dec))/Math.pow(10,decimals)); var dot = dec.indexOf('.'); if(dot == -1){ dec += '.'; dot = dec.indexOf('.'); } while(dec.length <= dot + decimals) { dec += '0'; } result = dec; } else{ var dot; var dec = new String(whole); dec += '.'; dot = dec.indexOf('.'); while(dec.length <= dot + decimals) { dec += '0'; } result = dec; } return result; } </script>
Copy the following code between the <BODY></BODY> tags of your html page.<input name="x" id="x" type="text"> <input name="y" id="y" type="button" value="Format in 2 decimal places." onClick="javascript: format_numberex(document.all.x.value,2);">
Enter your name and email address to have this script sent right to your Inbox for later viewing. First Name Last Name Email