Jump to content

Is user is asked for a number, is there any easy way to add a "0" and "00" to numbers below 100 ("0" for 1-9, "00" for 10-99)?


Go to solution Solved by Gianni,

Recommended Posts

If I have this in my GUI and numbers are asked for:

$Input1 = GUICtrlCreateInput("", 15, 40, 30, 25)     ; left, top, width, height

which is then output like this:

ClipPut("Pg." & GUICtrlRead($Input1) & "- " & $StandardDateSHORT & ".pdf")

is there an easy way to ensure if the input is less than 100, i.e., 1-99, that a zero gets added to 1-9 and two zeros before 10-99 automatically without the user worrying about any of that?

I ask because sometimes code to do this is easy - i.e., in my MP3 tag app, I just have to choose the right syntax for this type of thing to happen automatically, zero padding or soemthing I think it's called.

Just wondering if there was something easy enough to build right into my AutoIt GUI to ensure that any number comes out in the right format without bother to the user.

No worries if not, just would like to make this GUI truly automated in its output.

Thank you!

Link to comment
Share on other sites

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

  • Moderators

Diana (Cda),

StringFormat is what you need: :)

#include <MsgBoxConstants.au3>

MsgBox($MB_SYSTEMMODAL, "0 Padded", StringFormat("%03i", 9) & @CRLF & StringFormat("%03i", 10))
%    - Format code string begins
0    - Add leading zeros...
3    - ...to make string this length
i    - Use integer format
M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

I'll 'ave a go,

; "...if the input is less than 100, i.e., 1-99, that a zero gets added to 1-9 and
; two zeros before 10-99 automatically..."

Local $iNumber = 8, $sNum = $iNumber

If $iNumber >= 1 And $iNumber <= 9 Then $sNum = "0" & $iNumber
If $iNumber > 9 And $iNumber <= 99 Then $sNum = "00" & $iNumber

MsgBox(1, "Padded Zeros Mk1", $sNum)
;---------------------------------------------------------------------

;or
Local $iNumber = 8
MsgBox(1, "Padded Zeros Mk2", (($iNumber >= 1 And $iNumber <= 9) ? "0" : (($iNumber > 9 And $iNumber <= 99) ? "00" : "")) & $iNumber)

#cs  Test Results:-
    Number    Result
     -8          -8    ; Out of range
      8          08     ; A zero gets added to 1-9
     58        0058    ; Two zeros before 10-99
    108         108    ; Out of range
#ce

or two.

Link to comment
Share on other sites

I'll 'ave a go,

; "...if the input is less than 100, i.e., 1-99, that a zero gets added to 1-9 and
; two zeros before 10-99 automatically..."

Local $iNumber = 8, $sNum = $iNumber

If $iNumber >= 1 And $iNumber <= 9 Then $sNum = "0" & $iNumber
If $iNumber > 9 And $iNumber <= 99 Then $sNum = "00" & $iNumber

MsgBox(1, "Padded Zeros Mk1", $sNum)
;---------------------------------------------------------------------

;or
Local $iNumber = 8
MsgBox(1, "Padded Zeros Mk2", (($iNumber >= 1 And $iNumber <= 9) ? "0" : (($iNumber > 9 And $iNumber <= 99) ? "00" : "")) & $iNumber)

#cs  Test Results:-
    Number    Result
     -8          -8    ; Out of range
      8          08     ; A zero gets added to 1-9
     58        0058    ; Two zeros before 10-99
    108         108    ; Out of range
#ce

or two.

 

Thanks so much, Malkey!  The second one looked like the most recyclable for me.  But it seems like I'm doing something wrong again <sigh>.  I've tried every which way I can think of to balance the brackets, as I'm getting a balance brackets error, but no go.  My lack of actual programming training again, I guess, despite being a power user.

Here is how I structured it to use and re-use, and once the brackets are balanced, I think and hope it'll work really nicely.

p.s., I always use $input1 for input GUIs, so it's safe to keep that.  And putting the variable as $ZeroPadding seems like the easiest for me to work with down the road.  Anyway, here's what I have translated so far into the GUI and, if I've interpreted this correctly (?), I think should work once fixed (?):

$ZeroPadding = ($Input1 >= 1 And $Input1 <= 9) ? "00" : (($Input1 > 9 And $Input1 <= 99) ? "0" : "")) & $Input1)
;----------------------------------------------------------------------------------------------------------------------------
ClipPut("Pg." & GUICtrlRead($ZeroPadding) & "- " & $StandardDateSHORT & ".pdf")

Oh, I did change the zeroes for the zero padding.  Since I need 3 places, 1-9 get 2 zeroes, and 10-99 gets only one.  That's the only change to the output format.  That way, I'll always get something like this:  001, 002, 003, 010, 019, 029, 044, 179, 832 ...

I'm not worrying yet about going above 999 (i.e., going into 4 number places) at this time.  I guess I'll know soon enough if I have the potential to generate more than 999 log pages; if that turns out to be the case, I'm guessing I can adjust that padding by adding an extra zero to each of the 2 items above in the $ZeroPadding line, as well as adding a reference to >999, somehow ...

Thank you!

Edited by Diana (Cda)
Link to comment
Share on other sites

Hoping you will find what you can use in this example.

Local $Input1 = 8

#cs This following example returns :-
     8 to   08
    67 to 0067
    I believe this format was asked for in Post#1
#ce
$ZeroPadding = (($Input1 >= 1 And $Input1 <= 9) ? "0" : (($Input1 > 9 And $Input1 <= 99) ? "00" : "")) & $Input1
ConsoleWrite($ZeroPadding & @LF)
ConsoleWrite("-----------" & @LF)
; =======================================================================

#cs The following examples returns :-
     8 to 008
    67 to 067
#ce
$ZeroPadding = (($Input1 >= 1 And $Input1 <= 9) ? "00" : (($Input1 > 9 And $Input1 <= 99) ? "0" : "")) & $Input1
ConsoleWrite($ZeroPadding & @LF)
; ---------------- or ----------------------

$ZeroPadding = StringRight("000" & $Input1, 3) ; Returns the right most 3 characters.
ConsoleWrite($ZeroPadding & @LF)
; ---------------- or ----------------------

; Use StringFormat() function as Melba post#3 and Chimp post#6 have done.
Link to comment
Share on other sites

I've only scanned this question quickly, but I always just use a very simple StringRight method.

$num = StringRight("00" & $num, 3)

If $num is a single digit, then two zero's are added at start.

If $num is two digits, then one zero is added at start.

This is because the function reads number of characters from right to left, and any extra to the left is omitted.

This is very flexible, because if you wish your String to be four numbers, you just pad with an extra zero and increase the count, and so on.

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

P.S. In your case, if you are only after two digits, then it is - $num = StringRight("0" & $num, 2)

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

Link to comment
Share on other sites

Dana,

See M23's response (#3).  It is no more complicated than this... 

ClipPut("Pg." & stringformat('%03i',GUICtrlRead($Input1)) & "- " & $StandardDateSHORT & ".pdf")

kylomas

edit:

1-99, that a zero gets added to 1-9 and two zeros before 10-99

 

Do you really mean...

 1-99, that two zeros gets added to 1-9 and one zeros before 10-99

Edited by kylomas

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Link to comment
Share on other sites

  • 3 weeks later...

 

I think this is what you need

ClipPut("Pg." & StringFormat("%03i", GUICtrlRead($Input1)) & "- " & $StandardDateSHORT & ".pdf")

 

So sorry for delay in responding back.  I've been having crazy days again.  I think I broke a record recently - last week doesn't count as I was sick one day (so only a 44-hour, 4-day week there! <lol>), but the week before my Nexus work logger app is telling me I worked 71 hours and 14 minutes!!!  And it's been 2 months of craziness here where I work with those kinds of crazy hours <lol>. But I'm sure many of you can really relate to that ... <g>  But what a nice surprise to come here to try to catch up on things and find the perfect solution!  Woohoo!

<dancing a jig> - that code above is BRILLIANTLY simple!!  LOVE IT!  Easy peasy and it's done!  I just tried it and it tests out beautifully.  And since this script helps with an important task in my time management system, this just got streamlined down to nothing.  <sigh>

Thank you, Chimp, this is a super nifty solution and very much appreciated!  I'm saving this to my code snippets folder which always carry full references with including name, URLs, dates, times, so I'll always know who provided this lovely line that now truly allows me to just get the filename with path and off the document goes to it's safe saving spot!

Thanks so much!

Edited by Diana (Cda)
Link to comment
Share on other sites

If you want immediate change then try this example:

#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#Region ### START Koda GUI section ### Form=
$Form1 = GUICreate("Form1", 186, 84, 192, 124)
$Input1 = GUICtrlCreateInput("00", 64, 16, 49, 37, BitOR($GUI_SS_DEFAULT_INPUT,$ES_CENTER,$ES_NUMBER))
GUICtrlSetFont(-1, 18, 400, 0, "MS Sans Serif")
;GUICtrlSetLimit(-1,3)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###


While 1
    $Input1Read = GUICtrlRead($Input1)
    $tmp1 = StringFormat("%03i", $Input1Read)
    If $Input1Read <> $tmp1 Then GUICtrlSetData($Input1,$tmp1)
    If $Input1Read > 99 Then GUICtrlSetData($Input1,099)
    $nMsg = GUIGetMsg()


    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            Exit

    EndSwitch
WEnd
Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...