• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2180
  • Last Modified:

FORMAT DECIMAL PLACES AND PAD 0's

Hi
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
089.9000


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

0
Camnoc
Asked:
Camnoc
1 Solution
 
Göran AnderssonCommented:
Use the following function like this:

onblur="formatField(this,4,8);"
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

0
 
CamnocAuthor Commented:
Hi
Thanks very much. Much better code.

Thanks again
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now