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.

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.