它可能是最好與你的.ToString()
生成的字符串工作:
class Program
{
static string InsertSeparators(string s)
{
string decSeparator = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
int separatorPos = s.IndexOf(decSeparator);
if (separatorPos >= 0)
{
string decPart = s.Substring(separatorPos + decSeparator.Length);
// split the string into parts of 3 or less characters
List<String> parts = new List<String>();
for (int i = 0; i < decPart.Length; i += 3)
{
string part = "";
for (int j = 0; (j < 3) && (i + j < decPart.Length); j++)
{
part += decPart[i + j];
}
parts.Add(part);
}
string groupSeparator = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberGroupSeparator;
s = s.Substring(0, separatorPos) + decSeparator + String.Join(groupSeparator, parts);
}
return s;
}
static void Main(string[] args)
{
for (int n = 0; n < 15; n++)
{
string s = Math.PI.ToString("0." + new string('#', n));
Console.WriteLine(InsertSeparators(s));
}
Console.ReadLine();
}
}
輸出:
3
3.1
3.14
3.142
3.141,6
3.141,59
3.141,593
3.141,592,7
3.141,592,65
3.141,592,654
3.141,592,653,6
3.141,592,653,59
3.141,592,653,59
3.141,592,653,589,8
3.141,592,653,589,79
,因爲它是無效的。他們不會以同樣的方式分組(數千人,數十人,數百人),除非第一組是兩項:'3.14,159,265,358,979' – Plutonix 2014-10-05 12:23:46
咦?顯然需要從逗號開始,十分之一,百分之一和千分之一會成爲一個完美的正常組!這不是關於什麼 - 它是關於可讀性的! – TaW 2014-10-05 12:24:50
@TaW有點主觀,但它對我來說不可讀。數字組逗號提示它是一個很大的數字(數千億或者某個東西),直到你找到點,這看起來很奇怪。這不是一種常用的格式,這可能是它不起作用的原因。在你提出問題之前,我不會猜想有人會想這樣來格式化他們的數字。 – BartoszKP 2014-10-05 12:45:19