Metode ekstensi:
public static class Extensions
{
public static string TrimDouble(this string temp)
{
var value = temp.IndexOf('.') == -1 ? temp : temp.TrimEnd('.', '0');
return value == string.Empty ? "0" : value;
}
}
Kode contoh:
double[] dvalues = {20, 20.00, 20.5, 20.5000, 20.125, 20.125000, 0.000};
foreach (var value in dvalues)
Console.WriteLine(string.Format("{0} --> {1}", value, value.ToString().TrimDouble()));
Console.WriteLine("==================");
string[] svalues = {"20", "20.00", "20.5", "20.5000", "20.125", "20.125000", "0.000"};
foreach (var value in svalues)
Console.WriteLine(string.Format("{0} --> {1}", value, value.TrimDouble()));
Keluaran:
20 --> 20
20 --> 20
20,5 --> 20,5
20,5 --> 20,5
20,125 --> 20,125
20,125 --> 20,125
0 --> 0
==================
20 --> 20
20.00 --> 2
20.5 --> 20.5
20.5000 --> 20.5
20.125 --> 20.125
20.125000 --> 20.125
0.000 --> 0