iT邦幫忙

8

【C#】什麼? 123.ToString(format:"#,#,#")不是1,2,3

c#

首先大家看到以下代碼,第一直覺結果會是什麼 :

var result = 1234.56.ToString("#,#,#.##");
Console.WriteLine(result);

答案是1,234.56不是1,2,3,4.56

原因是ToString(string format)方法預設使用Thread.CurrentThread.CurrentCulture,以我個人電腦而言NumberGroupSzies屬性是3,導致最起碼需要3個數字才會加上逗號

ToString源碼 :

[SecuritySafeCritical]
[__DynamicallyInvokable]
public string ToString(string format)
{
	return Number.FormatDouble(this, format, NumberFormatInfo.CurrentInfo);
}

[__DynamicallyInvokable]
public static NumberFormatInfo CurrentInfo
{
	[__DynamicallyInvokable]
	get
	{
		CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
		if (!currentCulture.m_isInherited)
		{
			NumberFormatInfo numInfo = currentCulture.numInfo;
			if (numInfo != null)
			{
				return numInfo;
			}
		}
		return (NumberFormatInfo)currentCulture.GetFormat(typeof(NumberFormatInfo));
	}
}

假如想要按上面format方式,我們也只需要修改NumberGroupSzies屬性等於1就可以

CultureInfo culture = new CultureInfo(string.Empty, true)
{
    NumberFormat = { NumberGroupSizes = new int[] { 1 } }
};
Console.WriteLine(1234.56.ToString("#,#,#.##", culture));

以上問題來源於今天看到的有趣問題c# - decimal number comma styling - Stack Overflow

簡單小趣聞分享給大家 ^_^


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言