Posted on 2008-10-01
Medium Priority
Last Modified: 2010-04-21
I am using the following script's attached  to format decimal places and pad zeros.
Is there a way to combine both pieces of code. At present one will undo the other
What I need is if I enter 8 ,  On Change  It becomes 008.0000 or if I enter 89.9  On Change it becomes

Decimal places          onchange="fix(this)" 
function fix(o){
 if( !isNaN(parseInt(o.value,10)) )
    o.value = parseInt(o.value).toFixed(4);
Pad zeros     onblur="padValue(this,3);"
function pad(num, count) {
var lenDiff = count - String(num).length;
var padding = "";
if (lenDiff > 0)
while (lenDiff--)
padding += "0";
return padding + num;
function padValue(el, count) {
var num = Number(el.value);
if ( isNaN(num) ) {
alert("Please only enter numbers");
} else {
el.value = pad(num, count);

Open in new window

Question by:Camnoc
LVL 29

Accepted Solution

Göran Andersson earned 2000 total points
ID: 22612638
Use the following function like this:

function formatField(obj, decimals, len) {
   var n = Number(obj.value);
   if (!isNaN(n)) {
      var s = parseInt(n).toFixed(decimals);
      while (s.length < len) s = '0' + s;
      obj.value = s;
   } else {
      alert("Please only enter numbers");

Open in new window


Author Closing Comment

ID: 31501886
Thanks very much. Much better code.

Thanks again

Featured Post

Train for your Pen Testing Engineer Certification

Enroll today in this bundle of courses to gain experience in the logistics of pen testing, Linux fundamentals, vulnerability assessments, detecting live systems, and more! This series, valued at $3,000, is free for Premium members, Team Accounts, and Qualified Experts.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
A while back, I ran into a situation where I was trying to use the calculated columns feature in SharePoint 2013 to do some simple math using values in two lists. Between certain data types not being accessible, and also with trying to make a one to…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

621 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question