I want to write a function that format int
and decimal
differently into string
I have this code:
and I want to rewrite it to generics:
public static string FormatAsIntWithCommaSeperator(int value)
{
if (value == 0 || (value > -1 && value < 1))
return "0";
return String.Format("{0:#,###,###}", value);
}
public static string FormatAsDecimalWithCommaSeperator(decimal value)
{
return String.Format("{0:#,###,###.##}", value);
}
public static string FormatWithCommaSeperator<T>(T value) where T : struct
{
string formattedString = string.Empty;
if (typeof(T) == typeof(int))
{
if ((int)value == 0 || (value > -1 && value < 1))
return "0";
formattedString = String.Format("{0:#,###,###}", value);
}
//some code...
}
/// <summary>
/// If the number is an int - returned format is without decimal digits
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string FormatNumberTwoDecimalDigitOrInt(decimal value)
{
return (value == (int)value) ? FormatAsIntWithCommaSeperator(Convert.ToInt32(value)) : FormatAsDecimalWithCommaSeperator(value);
}
How can i use T in the function body?
What syntax should I use?