Custom formats are described at:
http://msdn2.microsoft.com/en-us/library/0c899ak8(VS.90).aspx
Standard formats are described at:
http://msdn2.microsoft.com/en-us/library/dwhawy9k(VS.90).aspx
In either case the Object data type does not support a native overloaded
ToString(format) method. Yes I can do the following:
if (_val.GetType() == typeof(System.Double))
{
double db = Convert.ToDouble(_val);
_host.Text = db.ToString(_format);
}
else if (_val.GetType() == typeof(System.Single))
{
float fl = Convert.ToSingle(_val);
_host.Text = fl.ToString(_format);
}
else if (_val.GetType() == typeof(System.Int16))
{
Int16 i16 = Convert.ToInt16(_val);
_host.Text = i16.ToString(_format);
}
else if (_val.GetType() == typeof(System.Int32))
{
Int32 i32 = Convert.ToInt32(_val);
_host.Text = i32.ToString(_format);
}
else if (_val.GetType() == typeof(System.Int64))
{
Int64 i64 = Convert.ToInt64(_val);
_host.Text = i64.ToString(_format);
}
but I was hoping there was a better way.
I'm missing something? I thought String.Format took custom format
strings...What about something as simple as:
class Program
{
static string FuncTest(string format, object obj)
{
// Parameter check here - format not null, object not
null, object type valid, etc...
string realFormatString = "{0:" + format + "}";
return string.Format(realFormatString, obj);
}
static void Main(string[] args)
{
double MyPos = 19.95234, MyNeg = -19.9551325, MyZero =
0.0;
// In the U.S. English culture, MyString has the value:
$19.95.
string MyString = FuncTest("$#,##0.00;($#,##0.00);Zero",
MyPos);
// In the U.S. English culture, MyString has the value:
($19.96).
// The minus sign is omitted by default.
MyString = FuncTest("$#,##0.00;($#,##0.00);Zero", MyNeg);
// In the U.S. English culture, MyString has the value:
Zero.
MyString = FuncTest("$#,##0.00;($#,##0.00);Zero", MyZero);
int iMyPos = 19, iMyNeg = -19, iMyZero = 0;
// In the U.S. English culture, MyString has the value:
$19.00.
MyString = FuncTest("$#,##0.00;($#,##0.00);Zero", iMyPos);
// In the U.S. English culture, MyString has the value:
($19.00).
// The minus sign is omitted by default.
MyString = FuncTest("$#,##0.00;($#,##0.00);Zero", iMyNeg);
// In the U.S. English culture, MyString has the value:
Zero.
MyString = FuncTest("$#,##0.00;($#,##0.00);Zero",
iMyZero);
}
}