Formatting numbers

I have an intger say, int testnum=21, or 1234 & want to format whatever value it has to be a fixed number of digits:

intnum.ToString(???) to give 00021 or 01234…
Is this possible?
It seems some of the ToString formatting options don’t work in NETMF. If not, not sureof the best way to do so using string manipulation functions

If they don’t, how about something like debug.Print((“00000” + testnum.ToString()).Substring(testNum.ToString().Length)) ?

Thanks–I suppose that might work, though it appears “slow”, with all the string manipulations going on

Maybe something in here will do the trick: http://netmfcommonext.codeplex.com/

If you don’t need a flexible, terribly re-usable library. Ie, you know the range you’re getting, and what length you want.

e.g. NumberIn is 0 to 1000, and you want 6 digits, zero padded.


string formatLeadingZero(int NumberIn, int LeadingZeros)
{
 if (NumberIn <10) return  "00000" + NumberIn.ToString(); 
 if (NumberIn >10) & (NumberIn <100) return  "0000"  +  NumberIn.ToString();
 if (NumberIn >100) & (NumberIn <1000) return Zeros = "0000" + NumberIn.ToString();
//... and so on.
 return (NumberIn.ToString() );// if all else.
}

You still have to use ToString() as an int is an int, leading zeros is only relevent when casting to a string. The most effiecient function will be biased for a default and the order of IF statements in the order of most to least likely so the function can exit as soon as it has an answer. Id hvae to test, but in small ranges of size I’ll be this is quicker than the alternative of…


string NumberToFixed(int NumberIN)
string Ints = NumberIn.ToString(); 
return = new String('0',6 - Ints.Length()) & Ints;

@ Dr9 - What about the ‘sign’ in both approaches? An int can be negative you know :wink:

You could use something like this (2 GC allocations):


public static string NumberToString(uint number, int places)
{
    char[] buffer = new char[10];// the size of this array limits maximum number of places
    int i;
    for (i = (buffer.Length - 1); (i >= 0) && ((number > 0) || (places > 0)); --i, number /= 10, --places)
        buffer[i] = (char)('0' + (number % 10));
    ++i;
    return new string(buffer, i, buffer.Length - i);
}

or with static buffer (only 1 GC allocation):


public static char[] buffer = new char[10];// the size of this array limits maximum number of places
public static string NumberToString(uint number, int places)
{
    lock (buffer)
    {
        int i;
        for (i = (buffer.Length - 1); (i >= 0) && ((number > 0) || (places > 0)); --i, number /= 10, --places)
            buffer[i] = (char)('0' + (number % 10));
        ++i;
        return new string(buffer, i, buffer.Length - i);
    }
}

In both cases you can add this overload for ‘int’ support:


public static string NumberToString(int number, int places)
{
    string sign;
    if (number < 0)
    {
        sign = "-";
        number = -number;
    }
    else
    {
        sign = "";
    }
    return sign + NumberToString((uint)number, places);
}

@ WouterH true, I was going in assuming santized and predictable inputs. I started to include # of digits on the function signature but went for the simplest solution.

Your solution is better in terms of and reuse and completeness.

BTW Why pre-increment?

It’s a habit from the times I was using old C compilers. Some of them compiled post increment in 2 assembly instructions instead of one (first instruction pushed the original value on stack before incrementing). Not that it matters anymore :slight_smile:

how about (for small positive values):

Not sure if it would be faster to use ToString in each return such as:
return(“000”+value.ToString());

NOTE: the zeros could be replaced by spaces to give a column-aligned right justification (say you had values 13, 765, 3356):

…13
…765
…3356

        private static string fixlen(int value, short numdigits)
        {  
            string raw=value.ToString();
            switch (numdigits - raw.Length) //find number of zeros to prefix
            { case 1:
                return ("0"+raw);         
              case 2:
                return ("00"+raw);             
              case 3:
                return ("000"+raw);           
              case 4:
                return ("0000"+raw);            
              case 5:
                return ("00000"+raw);           
              case 6:
                return ("000000"+raw);          
              default:
                return (raw);
            }

            Debug.Print("HERE IS "+ fixlen(123,1));
            Debug.Print("HERE IS " + fixlen(123, 2));
            Debug.Print("HERE IS " + fixlen(123, 3));
            Debug.Print("HERE IS " + fixlen(123, 4));
            Debug.Print("HERE IS " + fixlen(123, 5));
            Debug.Print("HERE IS " + fixlen(123, 6));
            Debug.Print("HERE IS " + fixlen(123, 7));

[quote]
HERE IS 123
HERE IS 123
HERE IS 123
HERE IS 0123
HERE IS 00123
HERE IS 000123
HERE IS 0000123[/quote]