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

首先大家看到以下代码,第一直觉结果会是什么 :

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

简单小趣闻分享给大家 ^_^


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章