Tuesday, April 5, 2011

How to format your number the CLR style

Converting (real) numbers to a string representation is a common requirement. There are different roads that lead to Rome, I'll show you some alternatives, which all have one thing in common: They all use Format.

You can use num2str to convert your real numbers to a string, or you can use Format.
Example, controlling the number of decimals showed:  (decimal point acts as decimal separator)

static void FormatExamples(Args _args)
{
    real        mynumber=123.4;
    String30    mynumberstr = System.String::Format("{0,0:#.00}", mynumber);
    ;
    info(strfmt("Your number is %1", mynumberstr));
}

You can use the Format command to add leading zeros also.
Example:

static void FormatExamples(Args _args)
{
    real        mynumber=123;
    String30    mynumberstr = System.String::Format("{0,0:00000}", mynumber);
    ;
    info(strfmt("Your number is %1", mynumberstr));
}

Notice that you can also use rounding like this as well.  Besides this basic function, we can actually do some conversions.
You can use Format to convert to hexadecimal for example.
Example:

static void FormatExamples(Args _args)
{
    int        mynumber=255;
    String30   mynumberstr = System.String::Format("{0,0:X}", mynumber);
    ;
    info(strfmt("Your number in Hex: %1", mynumberstr));
}

No comments:

Post a Comment