Posted on 2008-10-01
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 500 total points
Comment Utility
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

Comment Utility
Thanks very much. Much better code.

Thanks again

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Form submit issue 11 52
Log4Net custom Appender not being fired. 5 41
Javascript loop through list 13 32
Problem to page 4 16
In this article, we'll look how to sort an Array in JavaScript, including the more advanced techniques of sorting a collection of records either ascending or descending on two or more fields. Basic Sorting of Arrays First, let's look at the …
This article discusses how to create an extensible mechanism for linked drop downs.
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…

771 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

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now