Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1011
  • Last Modified:

Padding leading zeros and/or spaces on a Dollar amount in Javascript.

I need a function that I can run in Javascript that will allow me to pad a dollar amount with leading zeros or spaces.  For example, the number
198.76 would be
0000000000198.76 (total of 15 characters) or
          198.75 (total of 15 character w/leading spaces).

Would like the function to allow me to configure what the leading character will be.  This is need for a fixed format file that I am creating via Javascript.
0
Elroy Taulton
Asked:
Elroy Taulton
  • 7
  • 4
  • 2
2 Solutions
 
themrrobertCommented:
function addLead(strDollar, len, leadChar = "0") {
  result = strDollar;
  while(result.length < len) 
   result = leadChar + result;

  return result;
}

Open in new window


or if you don't know if the period and cents will be included:

// adds leading characters specified by leadChar, up
// to alength of len, on the string strDollar. 
// takes into account if there is a period and/or cents

function addLead(strDollar, len, leadChar = "0") {
  result = strDollar;
  dot = strDollar.indexOf('.') === -1 ? 0 : strDollar.len - strDollar.indexOf('.');

  while(result.length < (len+dot)) 
   result = leadChar + result;

  return result;
}

Open in new window


To also add trailing zeros:

// adds leading characters specified by leadChar, up
// to alength of len, on the string strDollar. 
// takes into account if there is a period and/or cents
// also adds trailing zeros unless the 4th param is set false.
function addLead(strDollar, len, leadChar = "0", addTrailingZeros = true) {
  result = strDollar;
  dot = strDollar.indexOf('.') === -1 ? 0 : strDollar.len - strDollar.indexOf('.');

  while(result.length < (len+dot)) 
   result = leadChar + result;

 if(addTrailingZeros)
 for(x=0; (x<3-dot); x++)
  result = "0" + result;

  return result;
}

Open in new window

0
 
Elroy TaultonDevelopment ManagerAuthor Commented:
This did not work for me. When I ran as listed (see below); I received an Invalid parameter 1 declaration for function.  When I modified it (second example below), it ran but did not place any leading zeros.  I think the problem is when it is recalculating the result, it is dropping the added zero then.

I might need the function to take the number (with the decimal) and convert it to a string, then I can add zeros.

function NPad(strDollar, len, leadChar = "0")
      {
            result = strDollar;
      
            while (result.length < len)
                  {
                        result = leadChar + result;
                  }
            return result;
      }


<MODIFIED>
function NPad(strDollar, len)
      {
            leadChar = "0"
            result = strDollar;
      
            while (result.length < len)
                  {
                        result = leadChar + result;
                  }
            return result;
      }
0
 
themrrobertCommented:
This html page works perfectly for me:

<html>
<head>
</head>

<script language="JavaScript" type="text/javascript"><!--

function NPad(strDollar, len)
      {
            leadChar = "0"
            result = strDollar;
      
            while (result.length < len)
                  {
                        result = leadChar + result;
                  }
            return result;
      }
	  
	  -->
</script>

<body>


<a onClick="alert(NPad('43.12',15)); return false;">Click Me</a>
</body>

</html>

Open in new window


I used the code you modified from me at the very end. This was the result I got:

000000000043.12

How are you actually calling the code, maybe i can help you there?
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Elroy TaultonDevelopment ManagerAuthor Commented:
I have an app that uses workflow and I have the ability to perform task as inbound/outbound actions via (a sudo javascript).  I have added a little more code that kinda shows what I am doing below.  Everything works, just no leading zeros in my output file.  There are no error messages which leads me to believe that it is adding them but dropping them somewhere else.  

Is it possible to convert the numeric value into a string value and then add leading characters?  I ask because I believe ultimately, I may want to add leading spaces (instead of zeros).

<<<small piece of code>>>

var wfDoc.f3      = CPad(wfDoc.f3,15,"X");
var PinvVNum      = NPad(invVNum,15);

var fp = Clib.fopen("E:\\IO Files\\export\\output.txt","a");
var outputString = wfDoc.f3 + "," + PinvVNum;
Clib.fputs(outputString, fp);


function NPad(strDollar, len)
      {
            leadChar = "0"
            result = strDollar;
     
            while (result.length < len)
                  {
                        result = leadChar + result;
                  }
            return result;
      }
        
      
      
function CPad(ContentToSize,PadLength,PadChar)
      {
            var PaddedString=ContentToSize.toString();
      
            for(i=ContentToSize.length+1;i<=PadLength;i++)
                  {
                        PaddedString=PaddedString+PadChar;
                  }
            return PaddedString;
      }
0
 
Sar1973Commented:
I think that you should previously verifiy if the HTML input has some constraints on the format the user can input.
If you're sure that the input will always be something like "00001234.56", than the solution to your problem is to convert the string to number like this:
var myStr="0000000000198.76";
var myNMB=Number(myStr).toFixed(2);
if you want 2 decimals.

If you're looking for a function that validates the input OR replaces allowed characters which are not in a numeric format, then use something like this:
var myNMBVLD=/^([0-9])+\.([0-9]{2})$/;
var myTest=myNMBVLD.test(input.value);
OR
var myNMB=(input.value).replace(new RegExp(' ', 'gi'), ""); //TO REPLACE SPACES
0
 
Elroy TaultonDevelopment ManagerAuthor Commented:
@ Sar1973  Not sure if you read or understood the original question.  It's not an HTML input nor am I looking for a function that validates.  I am looking for a function that can pad a given value (or convert the value to a string - then pad) with a character that I will supply (in a script).  Either a leading zero or a character space.
0
 
Sar1973Commented:
I was generally referring to a Javascript function that may format your string.
Then, please specify:
1) how long is the string that the user may type
2) which characters are allowed
3) other informations you may consider relevant.
Only then I could develop a function that formats your string with algorythms like:
function formatNMB(myNMB) {
      var myStr;
      var myTST=True;
      for (i = 0; i < myNMB.length; i++) {
            if (myNMB.charAt(i)=="0" && myNMB.charAt(i-1)=="0") {
                  myTST=False;
            } else {
                  myStr=myStr+myNMB.charAt(i);
            }      
      }
      return myStr;
}
just to give an idea.
0
 
Elroy TaultonDevelopment ManagerAuthor Commented:
My original question:

I need a function that I can run in Javascript that will allow me to pad a dollar amount with leading zeros or spaces.  For example, the number
198.76 would be
0000000000198.76 (total of 15 characters) or
          198.75 (total of 15 character w/leading spaces).

Would like the function to allow me to configure what the leading character will be.  This is need for a fixed format file that I am creating via Javascript.


There is no user typing anything.  It is converting a value that it is getting from a database.  In this function, I am probably going to need to convert the dollar amount to a character first because we may need to pad it with character spaces.
0
 
Sar1973Commented:
I mean, the original string must come from somewhere: if from a database, you should know first which format is set for that field (for ex. numeric, max length 12 numbers+2 decimals). Then you can set an algorithm to manipulate it (for ex. if(len(myStr)<14) myNMB="00(14-L times)"+myStr). Clear...?
0
 
Elroy TaultonDevelopment ManagerAuthor Commented:
Yes, I am clear about what you are asking, but I don't think you understand.  The value (original string) can be from several different number fields with different sizes.  For example,
NUM(15), NUM(7), NUM(9), etc.

My function would need to handle ALL of them and return the correct value padded according the script.  When I call the function, I will tell it what field, the pad size and the PadChar.  What I have found is the easiest way to handle this is to convert it to a string and then pad.  The output is going into an ASCII file so it works.  

The following function seems to get what I need accomplished (straight and simple).  Thanks themrrobert for pointing me in the right direction.  Thanks for you time as well Sar1973.

function NPad(number,len,PadChar)
      {      
            number = number.toString();
            
            while (number.length < len)
                  {
                        number = " " + number;
                  }
            return number;
0
 
Sar1973Commented:
So, len is a variable parameter? If you do not have a maximum lenght of the original number, how can you set the number of zeros to be placed before the number itself?
0
 
Elroy TaultonDevelopment ManagerAuthor Commented:
The entire process is creating an output file for upload.  The upload for each field expects  a specific size.  For example, the field size expected is 15 total.  If the number is:
198.98 or
2789.03 or
65767789.00 -- the field when return will need to be 15. Thus we would get (if using zeros)

000000000198.98 or
000000002789.03 or
000065767789.00

I don't need to know the maximum length because if it is over 15 at the beginning, the function would not add anything leading zeros and the upload program would fail.  If its less, the function determines the length when the value is passed in and just loops until the desired length (also passed in) is reached.
0
 
Elroy TaultonDevelopment ManagerAuthor Commented:
And yes, LEN is a variable parameter that is passed in and the valued is determined by the program that is going to accept the output file.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 7
  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now