ZPad$() - pad a number with leading zeroes
Sometimes it is nice to have leading zeroes on a number. MMBasic helpfully removes these for you which means to have them, the number must be returned as a string.
Str$ in MMBasic is deceptively powerful and goes some way to replacing the missing (on Micromites at least) FORMAT$ and USING. It can be tricky to get your head round the functionality so think of this function as a wrapper for a specific form.
This tiddly Function returns a string of the integer value x, padded to (at least) length y with leading zeroes. I say at least because if x already exceeds y then nothing is added.
This is a newer version of this function; it is better as it uses inbuilt “primitive” functionality to do the padding rather than “re-inventing the wheel” by string slicing. Consequently it is very marginally faster - rough tests seem to indicate a 16% improvement in speed. It also eliminates the potential restriction of 127 characters on the desired string.
If the string version of the argument already exceeds the desired length, the original number is returned - e.g. if you ask for 1000 to be padded to 3 digits.
Syntax: =ZPad$(number,totalNumDigits)
Example: Print ZPad$(7,3)' returns “007”
Code:
Function ZPad$(x As Integer,y As Integer) ZPad$=Str$(x,y,0,"0") End Function
See Also
uFormat$() and StrE$() provide flexible formatting of numeric values
Hold your horses! A Note on Str$(): You should probably consider using Str$() as a stand-alone and not ZPad$() where-ever needed in your program - unless it is a lot and just makes the program flow better - see the penultimate line of HumanTime(). The complete functionality of Str$ can be a bit difficult to get to grips with, but learning to use it properly is a much better way and better understanding leads to better programs. ZPad$() assumes you only want to pad with zeroes. The overhead of calling this as a function is not inconsiderable - a loop of 1000 iterations at 48MHz takes 492mS, the same using Str$() explicitly takes 177mS - two-and-a-half times quicker. “Occasional” use won't be noticed, but if you are doing it a lot, consider using Str$().
That said, Str$() makes (reasonable) assumptions too. Suppose one where trying to pad the right of a string. Consider the following:
Print Str$(53,4,4,"*")
you might expect the string
**53.****
but the pad character (*) is ignored for the third argument (digits after the decimal point) and zero is mandated.
**53.0000