Jump to content

[SOLVED] concatinate a zero at front of string


stockton

Recommended Posts

I have a string = "305208001" and I need to use it in my database with a zero in front. In other words the database field must be 10 digits long and in this case prefixed with a zero.

I have tried

if (lastnum.length < 10) lastnum = 0 + lastnum;

but when I do an alert it seems to supress the zero.

alert("BatchSize = "+bsize+" FirstNumber = "+firstnum+" Lastnum = "+lastnum);

I have also tried

    if (lastnum.length < 10) lastnum = 0 + lastnum.toString();

as well as

lastnum.toString();

if (lastnum.length < 10) lastnum = 0 + lastnum;

all without success.

Link to comment
Share on other sites

hi

 

im no js expert, but i think using 0 + x makes it a numeric function, and using '0' + x makes it a string frunction, so try something like

 

if (lastnum.length < 10) lastnum = '0' + lastnum;

or

if (lastnum.length < 10) lastnum = '0' + lastnum.toString();

 

but you probably want to write an actual function for this as the number might only be 8 characters long etc

something like

function strpad(num)
{
  while (num.length < 10)
  { num = '0' + num.toString(); }
  return num;
}

lastnum = strpad(lastnum);

 

good luck,

tdw

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.