首页 > 解决方案 > 为什么 .net C# float 在字符串表示中被截断为千位?

问题描述

以下怎么可能?

immediate console:
"{0:F20},{1:F20}, {2:F20}".format(
     res_ts, // float
     AppMgr.logon_info.res_ts, //float
     res_ts - AppMgr.logon_info.res_ts
)
"{0},{1}, {2}".format(
     res_ts, 
     AppMgr.logon_info.res_ts, 
     res_ts - AppMgr.logon_info.res_ts
)

result:
"3791785000.00000000000000000000,
 3791785000.00000000000000000000, 
       -512.00000000000000000000"
"3.791785E+09,
 3.791785E+09, 
-512"

为什么它们看起来一样但有-512的差异? res_tsAppMgr.logon_info.res_ts字符串存储和重新加载。

更新: .Net4 上的一些简单测试:

float a = 3791785472f;
Console.WriteLine(String.Format("{0:F20}, {1}",a, a) );
Console.WriteLine(String.Format("{0:0.#}, {1:00.#}",a, a) );
Console.WriteLine(String.Format("{0:0.#}, {1:0,0.#}",a, a) );
Console.WriteLine(String.Format("{0:#.#}, {1:0,0.#}",a, a) );

结果:

3791785000.00000000000000000000, 3.791785E+09
3791785000, 3791785000
3791785000, 3,791,785,000
3791785000, 3,791,785,000

链接:https ://dotnetfiddle.net/hTEFGr

在字符串表示中,所有内容都被截断为千位。我想知道我应该怎么做才能将一个大浮点数保存为字符串而不截断到千位?

更新:

double a = 3791785472f;
Console.WriteLine(String.Format("{0:F20}, {1}",a, a) );
Console.WriteLine(String.Format("{0:0.#}, {1:00.#}",a, a) );
Console.WriteLine(String.Format("{0:0.#}, {1:0,0.#}",a, a) );
Console.WriteLine(String.Format("{0:#.#}, {1:0,0.#}",a, a) );

3791785472.00000000000000000000, 3791785472
3791785472, 3791785472
3791785472, 3,791,785,472
3791785472, 3,791,785,472

哎呀。但是为什么没有溢出或任何类型的错误?听起来像是一项冒险的业务。也许我应该尽可能地避免浮动?

标签: c#.netfloating-pointformattingtruncate

解决方案


推荐阅读