How to pad string with leading zeroes

*** please ignore the post entitled 'Brian'. Its a duplicate of
*** this post without a matching title

Hi,

I have a requirement to convert a 3-digit integer to a 3 character string 
padded with leading zeroes as I SELECT it from the database. 

Examples:
=========

1 converts to '001'

21 converts to '021'

321 converts to '321'


I have played with several string functions to no avail. Any 
help/suggestions would be appreciated.

Brian 
0
Brian
7/27/2001 9:21:36 PM
sybase.ase.general 8655 articles. 0 followers. Follow

3 Replies
7685 Views

Similar Articles

[PageSpeed] 6

Two possible ways to get you going:

select substring(convert(char(4),column + 1000),2,3)

OR

select replicate('0',3 - datalength(convert(varchar(3),column))) +
convert(varchar(3),column)

Bob Densmore

<Brian> wrote in message
news:601B2A5FC5638C45007555BF85256A96.007555D285256A96@webforums...
> *** please ignore the post entitled 'Brian'. Its a duplicate of
> *** this post without a matching title
>
> Hi,
>
> I have a requirement to convert a 3-digit integer to a 3 character string
> padded with leading zeroes as I SELECT it from the database.
>
> Examples:
> =========
>
> 1 converts to '001'
>
> 21 converts to '021'
>
> 321 converts to '321'
>
>
> I have played with several string functions to no avail. Any
> help/suggestions would be appreciated.
>
> Brian


0
Bob
7/27/2001 9:45:30 PM
Another way is:

select XX = right ('00'  +  convert (varchar (3), YY)), 3)

However all three techniques will have problems with negative numbers.
Unless you LITERALLY mean "pad on the left with zeroes" (e.g., "0-5").  You
may have to use one of the three techniques with a union.  Even then, it
seems tricky to me.



"Bob Densmore" <bob.densmore@dhs.state.tx.us> wrote in message
news:kKfotjuFBHA.262@forums.sybase.com...
> Two possible ways to get you going:
>
> select substring(convert(char(4),column + 1000),2,3)
>
> OR
>
> select replicate('0',3 - datalength(convert(varchar(3),column))) +
> convert(varchar(3),column)
>
> Bob Densmore
>
> <Brian> wrote in message
> news:601B2A5FC5638C45007555BF85256A96.007555D285256A96@webforums...
> > *** please ignore the post entitled 'Brian'. Its a duplicate of
> > *** this post without a matching title
> >
> > Hi,
> >
> > I have a requirement to convert a 3-digit integer to a 3 character
string
> > padded with leading zeroes as I SELECT it from the database.
> >
> > Examples:
> > =========
> >
> > 1 converts to '001'
> >
> > 21 converts to '021'
> >
> > 321 converts to '321'
> >
> >
> > I have played with several string functions to no avail. Any
> > help/suggestions would be appreciated.
> >
> > Brian
>
>


0
Carl
7/28/2001 3:24:05 PM
/* Good for positive and negative numbers. */


1> select field1, "Both Signs" =
2>        substring( "- +", (sign(field1) + 2), 1) +
3>        right( replicate("0", 12) + convert(varchar, abs(field1)), 12)
4> from tempdb..Numbers
5> go
 field1      Both Signs 
 ----------- ------------- 
        1000 +000000001000 
       -1000 -000000001000 
           0  000000000000 

(3 rows affected)
0
wkraatz
7/30/2001 1:57:19 PM
Reply:

Similar Artilces:

Leading zero in a string
Hi All, I have a variable I'm reading off of the command line: my $option = shift; That variable should hold a number between 1 and 31 (yes, a day of the month) I am checking to make sure that the number does indeed lie in that range. However, I need to pass that variable to another system command which expects any "day" value less than 10 to have a leading zero, so 7th day of the month should say '07'. How can I check for that leading zero? If it's missing, I know I could easily: $option = "0".$option; But I can't seem to figur...

Padding strings with zeros
here's a way to pad to 32 bits: sub _pad32 { substr("0" x 32 . shift, -32); } which is used in Image::Size in the following manner: # _bin2int - converts binary string to decimal sub _bin2int {unpack("N",pack("B32",substr("0"x32.shift,-32)));} >>>Schoeneman, Carl 09/26/01 08:40pm >>> Is there a way to pad a number with leading zeros with 1 command rather than the 2 I used below? It looks like you're supposed to be able to zero-fill with sprintf but I couldn't figure it out. _________________________...

Zero-width split() match creates empty trailing strings but not empty leading strings
The perlfunc documentation spells this out clearly, and it matches what I see: $ perl -e 'for (split(//, "fob", -1)) { print "$_\n"; }' | sed -e 's/^$/<blank>/' f o b <blank> The question on my mind is why. In particular, is it a decision worth replicating to language's libraries? Thanks for any pointers. I tried to find the source for split, and I think I may have found it in pp_split in pp.c. But there's not really any reason to expect the source code to include the justification, and I couldn't find one. http:/...

Pad Number with Leading Zeros
------_=_NextPart_001_01C146C3.16F952D0 Content-Type: text/plain; charset="iso-8859-1" Hello. Is there a way to pad a number with leading zeros with 1 command rather than the 2 I used below? It looks like you're supposed to be able to zero-fill with sprintf but I couldn't figure it out. #!/bin/perl -wd $f = 1234; $g = sprintf "%6s", $f; $g =~ s/ /0/g; print "$f\n"; print "$g\n"; ~Carl ------_=_NextPart_001_01C146C3.16F952D0-- ------_=_NextPart_001_01C146C7.025BA040 Content-Type: t...

Padding Numeric field with leading Zeros
Hi, I have a situation where I need to convert an Amount field into a CHAR field and pad it with leading Zeros, so that the total number of places occupied are 12 characters. for example : If the amount is $4.50 Then it should be converted as 000000000450 Has anyone done this in the past. If yes, could you please send me the methodology. Thanks. Regards, Murali. declare @VALUE int declare @i int select @i = 9 -- number of characters desired select @VALUE = -12345 /* leading sign */ SELECT CASE WHEN @VALUE >= 0 THEN "+" + r...

Padding Numeric field with leading Zeros #2
Hi, I have a situation where I need to convert an Amount field into a CHAR field and pad it with leading Zeros, so that the total number of places occupied are 12 characters. for example : If the amount is $4.50 Then it should be converted as 000000000450 Has anyone done this in the past. If yes, could you please send me the methodology. Thanks. Regards, Murali. ...

Converting numeric value to string with leading zeroes
Hi, We have a smallint column on a table in which we store ISO country numeric codes. These values range in length from 1 to 3 (when stored as smallint). However we now have a requirement that we output them to a flat file they must be of length 3 with leading zeroes if required e.g. 76 must be '076'. Obviously I could just do a few IF statements with DATALENGTH and STR but I was wondering if someone has a nice tidy way if doing it. Eoin > Obviously I could just do a few IF statements with DATALENGTH and STR but I > was wondering if someone has a nice tidy...

Autocomplete dropping leading zeros from results string array
Hi all, I am using the autocomplete control to retrieve values from a DB. When i do a search on a string beginning with a 0 the 0 is dropped from the results shown on screen. I have debugged the GetCompletionList method and the returning string array definetly has the leading zero's. As far as i can tell it only happens with the 0 character.   Any one have any ideas? Cheers,P.S. I am using .net 2.0 with ajax extensions 1.0   Hi WhatStherush, It is a known issue, please add the return items like this, myList.Add("\""+dr.GetString(0)+"\"&quo...

GridView & FormView dropping leading zeros from numbers set as strings
I'm storing in a SQL database a certain field (an employee number) as a varchar data type. Throughout the app (datasource, update/insert stored procedures, etc.) I'm working with it as a string. I've even ensured that it's being used as a string "behind the scenes" by watching it in SQL Profiler. Problem is, the GridView & FormView that display it always drop any leading zeros. Wierder yet, when I put the GridView in Edit mode & add a zero, it saves to the database with the zero, but the leading zero doesn't display in the GridView! Anyone kn...

Autocomplete dropping leading zeros and trailing zeros after a hyphen
Autocomplete Web Service Code 1    Imports System.Web2    Imports System.Web.Services3    Imports System.Web.Services.Protocols4    Imports System.Data.SqlClient5    Imports System.Data6    7    ' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.8    <System.Web.Script.Services.ScriptService()> _9    <WebService(Namespace:="http://tempuri.org/")> _10   <WebServiceBindi...

string padding
We=92re using PowerBuilder 10 (build 8011) and connecting to Microsoft SQL Server 2000 via ODBC. To prevent VARCHAR fields from being padded with spaces, we added the following lines to our pbodb100.ini file: PBTrimCatCharColumns=3d'YES' PBUseProcOwner=3d'YES' This works fine with DataWindows and embedded SQL, but VARCHAR values returned by reference as input/output parameters to stored procedures called via RPC are still being padded with spaces or truncated to match the length of the input parameter. For example, if we have a stored procedure foo, c...

String and string?
Hi guys, I was wondering the difference between small letter string type and a capital letter String type. Does anyone know about this? Highly appreciate for your answers! Thankz! The "proper" version is String, as it references the System.String class of the .NET Framework Class Library. The ability to use string is provided by C#, where it is an alias to String. Similarly, the "proper" version of an integer is Int32, as it references System.Int32.  The ability to use int is provided by C#, and the ability to use Integer is provided by VB.NET, and both int and Integer are aliases...

ASE to ASE
Hi, Is anyone out there doing ASE to ASE replication using SQL remote? If you are have created your own version of the SSEXTRACT utility to set up a replicant database in ASE rather than ASA? Or does anyone know if SYBASE has created a version SSEXTRACT for use with ASE to ASE replication? Thanks in advance Doug Trainer Hi Douglas, I thought the SQL Remote Replication support in ASE11.5 was meant for a consolidate-database only (by design)! At least that was what Sybase said when they announced support for SQL Remote technology support in ASE11.5. I will be happy to...

Leading zeroes
Hello, How can I suppress the leading zeroes, except one when all positions are 0; for example: 000015 will be 15 000000 will be 0 thank you. Olivier -- +++ GMX - die erste Adresse f�r Mail, Message, More +++ Neu: Preissenkung f�r MMS und FreeMMS! http://www.gmx.net Olivier Wirz wrote: > Hello, > > How can I suppress the leading zeroes, except one when all positions are 0; > for example: > > 000015 will be 15 > 000000 will be 0 This is a pretty vague question. How are you outputting the numbers? Are you writing to a file, using print...

string and string[]
hello, whats the difference here between string and string[] thanks "string" denotes an item of type String "string[]" denotes an array of type String itemsThanks, EdMicrosoft MVP - ASP/ASP.NET Gracia mon ami...

string() = string()
this code does not work (not instance of object) Dim Items(), Other() As String Items = New String() {"A","B","C"} Other = New String() {} Other = Items how can I get all the values ? angiras Hi, If I understand your requirement correctly, this should do it Dim Items() As String = {"A", "B", "C"} Dim Other(Items.Length - 1) As String Items.CopyTo(Other, 0) To more closely match you code above, but this will be less efficient Dim Items(), Other() As String ...

string to string[]
Hi, I've got this code : string[] Params; string SQL = "SELECT * FROM T_MANAGEMENT_PAGES"; SqlCommand myCommand = new SqlCommand(SQL, myConnection); myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); try { while (myReader.Read()) { Params_Type = myReader.GetValue(0).ToString(); } } catch { } finally { } myReader.Close(); My problem is to obtain Params_Type. But each time, it says : "impossible to convert '[object]' in 'string[]' &quo...

String and String[]
What will be the advantage of using myString: String[10] over myString: String Man wrote: > What will be the advantage of using > myString: String[10] > over > myString: String "String[10]" is a fixed-length, statically allocated, Ansi-based ShortString. "String" is a dynamic-length, dynamically allocated, reference counted, Ansi-based or Unicode-based (depening on Delphi version) Long string. Unless you absolutely need the static, fixed length nature of ShortString, such as in records that interact with external systems, you should stay ...

Zero Padding
I have a value (stored in a local variable) that I want to zero-pad to keep the length (number of chars) the same. Is there some easy way to do this? I was looking at XPATH and it seems like there are some formatting functions that could possible do this. Does anyone have a good example of how to do this? Thanks. Matt, Using IDM 3.5 I would add an ECMAScript function like the one shown at the foot of this posting to my Driver and then if I wanted to pad with zeros on the left to a length of 13 I would invoke it in a Policy similar to this: <do-set-local-variable na...

Leading Zero
Does anyone know of a existing problem from inetcfg bind then reinitialize system then the udp/tcp is putting in a leading zero at the third octect ....192.168.0.21 - 192.168.00.21...This is causing a problem of course....Help Gerald Cummings wrote: > Does anyone know of a existing problem from inetcfg bind then reinitialize > system then the udp/tcp is putting in a leading zero at the third octect > ...192.168.0.21 - 192.168.00.21...This is causing a problem of > course....Help Haven't seen that one... what version of netware, service packs, tcp/ip etc? Is...

What generals generally do
Reading a McChrystal thread elsewhere, I came across someone quoting a US general http://en.wikipedia.org/wiki/Smedley_Butler > I spent 33 years and four months in active military service and > during that period I spent most of my time as a high class thug for > Big Business, for Wall Street and the bankers. In short, I was a > racketeer, a gangster for capitalism. I helped make Mexico and > especially Tampico safe for American oil interests in 1914. I helped > make Haiti and Cuba a decent place for the National City Bank boys to > collect revenues in. I ...

Leading zeros?
I need help with leading zeros within the presentation layer of asp.net. I'm pulling a number from a sql database and display it on a textbox. I want that number to have leading zeros. Example: 149 I want that to be like 00149 or 1234 to be like 01234. I tried several examples provided within some of the previous threads but no luck. Example I use this one: varNum = String.Format("{0:00000}", varStr) Please advise. try something like this : Dim i As Integer, j As String, k As String, val as string i = 123 k = "00000" j = Convert.T...

Leading zeros
How can you place leading zeros on an integer before converting to string? You can't add leading 0's to the integer but why not do..... MyString = "00000" & str(MyInt) Mat Please try the following varStr = string.Format("{0:000000000}",varNum); ThanksSenthil Nathan http://www.chendhur.com Hi Try as below : Dim PadNbr As String = Trim(Str(12345)) Response.Write(PadNbr.PadLeft(Len(PadNbr) + 1, "0")) HTH K B ShajudeenAreYaar.comDubai, United Arab Emirates....

Leading zero ?!
Hi,I'm using Convert.ToString() method to convert Hour or Minute of a datetime format control to a string but it's not a leading zero string.  How can I do it ?Please help !cheers,stephen   I think you are using the wrong ToString try DateTime.ToString and System.TimeSpan.  Hope this helps.http://msdn2.microsoft.com/en-us/library/system.timespan.aspxhttp://msdn2.microsoft.com/en-us/library/k494fzbf.aspxKind regards,Gift Peddie  By using the DateTime's ToString and with a format expression, you can format the date into a string...

Web resources about - How to pad string with leading zeroes - sybase.ase.general

Leading - Wikipedia, the free encyclopedia
... here. For the city and metropolitan borough in West Yorkshire, England, see Leeds . For other uses, see Lead (disambiguation) . "Line leading" ...

Buckeye Nation? Ohio State Dominates Oregon in Facebook Conversation Leading Up to Title Game
While the University of Oregon is favored over Ohio State University in Monday night’s College Football Playoff National Championship Game Presented ...

Hürriyet Daily News - LEADING NEWS SOURCE FOR TURKEY AND THE REGION
Hurriyet Daily News is the leading news source for Turkey and the region. Hurriyet daily news, turkish daily news, turkish news, hürriyet daily ...

Is Developer Forum Activity a Leading Indicator of Facebook Platform Economy Health?
Facebook developer Jesse Farmer has slurped the Developer Forums for the last 3 months and found some powerful trends: since January, posts per ...

Tehran Times - Iran's Leading International Daily
Tehran Times - Iran's Leading International Daily

Leading Geeks (@LeadingGeeks) on Twitter
Sign in Sign up To bring you Twitter, we and our partners use cookies on our and other websites. Cookies help personalize Twitter content, tailor ...

Virtual-Strategy Magazine - Your leading source for virtualization news
Virtual Strategy Magazine is an online publication devoted entirely to virtualization technologies.

Daily Times - Leading News Resource of Pakistan
DailyTimes delivers the latest breaking news and information on the latest top stories, entertainment, business, cricket, politics, and more. ...

Mobile News Online - The UK's leading mobile communication industry news site
This month, thousands of students will be starting university for the first time. Some will need new phones. Mystery Caller is on the case to ...

Who are the UK’s Leading Social Business Influencers?
We have attempted to create a list of the top Social Business Influencers in and around the UK. These influencers have, through what they have ...

Resources last updated: 2/16/2016 5:51:13 PM