Jump to content
leuce

How to add leading zeros

Recommended Posts

Hello everyone

I saw in previous messages that one can use StringFormat to add leading zeros so a number so that the "number" (i.e. the string with leading zeros) always has a specific number of characters, but I'm afraid I don't understand how it works.  Can anyone here please tell me how?

At the moment, if I want to have leading zeros, I use something like this:

For $i = 1 to 100
$j = $i
If $i < 100000 Then
$j = "0" & $j
EndIf
If $i < 10000 Then
$j = "0" & $j
EndIf
If $i < 1000 Then
$j = "0" & $j
EndIf
If $i < 100 Then
$j = "0" & $j
EndIf
If $i < 10 Then
$j = "0" & $j
EndIf
Next

I use these numbers e.g. when creating file names and I want them to sort alphabetically correctly.  Thanks.

Samuel

Share this post


Link to post
Share on other sites

This way?

For $i = 1 To 100
    $j = $i
    If $i < 100000 Then
        $j = "0" & $j
    EndIf
    If $i < 10000 Then
        $j = "0" & $j
    EndIf
    If $i < 1000 Then
        $j = "0" & $j
    EndIf
    If $i < 100 Then
        $j = "0" & $j
    EndIf
    If $i < 10 Then
        $j = "0" & $j
    EndIf
    ConsoleWrite($j & ", StringFormat: " & StringFormat("%06i", $i) & @CRLF)
Next

"%06i" can be interpreted as. "%" is a literal, flag "0" for leading zeroes, width "6" means result is 6 characters wide, type "i" stands for signed integer.

Edited by water

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2020-09-05 - Version 1.5.1.1) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2020-06-27 - Version 1.6.1.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (NEW 2020-06-27 - Version 1.3.2.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
Task Scheduler (2019-12-03 - Version 1.5.1.0) - Download - General Help & Support - Wiki

Tutorials:
ADO - Wiki, WebDriver - Wiki

 

Share this post


Link to post
Share on other sites

Fails with negative values. StringFormat is more robust and flexible.


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

Something like what BigDaddyO suggested if you are dealing with a known fixed length.

I regularly use a variation of the following.

$num = StringRight("000" & $num, 4)

In that scenario, the initial source $num can be 1 to 1000 and you always get the correct 4 digit number with required leading zeroes.

EDIT - That 1000 might be misleading, as it could be as much as 9999 .... I was just illustrating in basic terms of 1 to 4 digits.

Edited by TheSaint

Make sure brain is in gear before opening mouth!
Remember, what is not said, can be just as important as what is said.

Spoiler

What is the Secret Key? Life is like a Donut

If I put effort into communication, I expect you to read properly & fully, or just not comment.
Ignoring those who try to divert conversation with irrelevancies.
If I'm intent on insulting you or being rude, I will be obvious, not ambiguous about it.
I'm only big and bad, to those who have an over-active imagination.

I may have the Artistic Liesense ;) to disagree with you. TheSaint's Toolbox (be advised many downloads are not working due to ISP screwup with my storage)

userbar.png

Share this post


Link to post
Share on other sites

looks like a fun thought experiment 'if stringformat did not exist', this one seems to play nice with negatives and existing leading zeroes:

#include<string.au3>

$n = -0066
$length = 7

msgbox(0, '' , (number($n) < 0 ? "-" : "") &  _StringRepeat(0 , $length - stringlen(Abs($n))) & Abs($n))

 

Edited by iamtheky

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites

LOL. I love it when code gets taken to the extremes.

About time we had some more code contests. :)

1. The simplest way to do something.

2. The most complex way.

3. The cleverest.

4. The dumbest.

P.S. No doubt a good learning experience on occasion.

Edited by TheSaint

Make sure brain is in gear before opening mouth!
Remember, what is not said, can be just as important as what is said.

Spoiler

What is the Secret Key? Life is like a Donut

If I put effort into communication, I expect you to read properly & fully, or just not comment.
Ignoring those who try to divert conversation with irrelevancies.
If I'm intent on insulting you or being rude, I will be obvious, not ambiguous about it.
I'm only big and bad, to those who have an over-active imagination.

I may have the Artistic Liesense ;) to disagree with you. TheSaint's Toolbox (be advised many downloads are not working due to ISP screwup with my storage)

userbar.png

Share this post


Link to post
Share on other sites

@TheSaint

When another one of those? :)


Click here to see my signature:

Spoiler

Thoughts:

  • I will always thank you for the time you spent for me.
    I'm here to ask, and from your response, I'd like to learn.
    By my knowledge, I can help someone else, and "that someone" could help in turn another, and so on.

/*--------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/

ALWAYS GOOD TO READ:

 

Share this post


Link to post
Share on other sites

... just for fun, a version that does not use StringFormat() nor #include <string.au3> nor regex

$nr = -0066
$length = 7

MsgBox(0, '', Num_Len($nr, $length))

Func Num_Len($n, $length)
    Local $a[$length]
    Return (Number($n) < 0 ? "-" : "") & StringRight(StringReplace(StringFromASCIIArray($a), Chr(0), '0') & Abs($n), $length)
EndFunc   ;==>Num_Len

 


small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Share this post


Link to post
Share on other sites
10 hours ago, FrancescoDiMuro said:

@TheSaint

When another one of those? :)

@czardas - was the mover and shaker behind them. If you are keen for some more, maybe let him know.


Make sure brain is in gear before opening mouth!
Remember, what is not said, can be just as important as what is said.

Spoiler

What is the Secret Key? Life is like a Donut

If I put effort into communication, I expect you to read properly & fully, or just not comment.
Ignoring those who try to divert conversation with irrelevancies.
If I'm intent on insulting you or being rude, I will be obvious, not ambiguous about it.
I'm only big and bad, to those who have an over-active imagination.

I may have the Artistic Liesense ;) to disagree with you. TheSaint's Toolbox (be advised many downloads are not working due to ISP screwup with my storage)

userbar.png

Share this post


Link to post
Share on other sites

Back to innocence example

#include <string.au3>
MsgBox(0, '', _ARLeadingZeros(-00066, True) & @CRLF & _ARLeadingZeros(-00066, False, 3))

Func _ARLeadingZeros($n, $bRemove = False, $length = 6)
    If $bRemove Or StringLen(Abs($n)) >= $length Then Return $n
    Local $nP = 1 & _StringRepeat(0, $length), $nN = "-" & StringTrimLeft($nP - $n, 1)
    Return $nN = $n ? $nN : StringTrimLeft($nP + $n, 1)
EndFunc   ;==>_AddRemoveLeadingZeros

 

Edited by Deye

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...