string display = FormatDecimalPlaces(ค่า deciaml, จำนวนจุดทศนิยมที่ต้องการ);
string display = FormatDecimalPlaces(31.02, 5);
ตัวอย่าง ต้องการทิศนิยม 5 ตำแหน่ง ถ้า input มีจุดทศนิยมเกิน 5 ก็ round ให้เหลือ 5 ตำแหน่ง
โค้ด: เลือกทั้งหมด
/* before -> after
1) 31 -> 31.00000
2) 31.1 -> 31.10000
3) 31.01 -> 31.01000
4) 31.55571 -> 31.55571
5) 31.555719-> 31.55572
*/
โค้ด: เลือกทั้งหมด
public string FormatDecimalPlaces(decimal input, string decimalPlaces)
{
try
{
decimal tmp = input;
//decimalPlaces = 2 -> patternSharp -> "0.##" , patternDot -> .00
//decimalPlaces = 5 -> patternSharp -> "0.#####" , patternDot -> .00000
int decP = 6;
try
{
decP = Convert.ToInt32(decimalPlaces);
}
catch
{
decP = 6;
}
string patternSharp = "0.";
string patternDot = ".";
for (int j = 0; j < decP; j++)
{
patternSharp += "#";
patternDot += "0";
}
if (tmp.ToString("0.######").IndexOf(".") > -1)
{
//แสดงว่ามีจุดทศนิยม
string a = tmp.ToString("0.######").Split('.')[0];
string b = tmp.ToString("0.######").Split('.')[1];
if (b.Length > decP)
{
// 5)
return Decimal.Round(input, decP).ToString(patternSharp);
}
else if (b.Length == decP)
{
// 4)
return input.ToString(patternSharp);
}
else if (b.Length < decP)
{
// 2) 3)
return a + "." + b.PadRight(decP, '0');
}
else
{
return input.ToString(patternSharp) + patternDot;
}
}
else
{
// 1)
return input.ToString(patternSharp) + patternDot;
}
}
catch
{
return input.ToString("0.######");
}
}