2017-04-12 86 views
0

“如何将浮动转换为字符串可以精确到一个小数”将浮点数转换为字符串。而不是,

这个问题已经被问了很多次,和通常的回答是MyFloat.ToString("0.0")或类似的东西。然而,我与这个所面临的问题是,

float f = 1; 
string s = f.ToString("0.0"); 
MessageBox.Show(s); 

输出1,0,但我需要的是1.0。之后我当然可以手动用逗号替换逗号,但我非常肯定这不会是正确的做法。 我无法在互联网上找到解决方案,因为无处不在说它已经输出1.0 怎么回事?

+0

和[此](http://stackoverflow.com/questions/9160059/set-up-dot-instead-of-comma- in-numeric-values)和[this](http://stackoverflow.com/questions/3870154/c-sharp-decimal-separator)... – Pikoh

回答

1

例如使用InvariantCulture的

string s = f.ToString("0.0", CultureInfo.InvariantCulture); 
4

您可以使用InvariantCultureToString

string s = f.ToString("0.0", CultureInfo.InvariantCulture); 

小数分隔符取决于文化,但InvariantCulture使用.这是你想要的。

0

通用的解决方案是:在当前区域性改变NumberDecimalSeparator

System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone(); 
customCulture.NumberFormat.NumberDecimalSeparator = "."; 
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture; 
float value1 = 3.55f; 
String message = String.Format("Value is {0}", value1); 
Console.Write(message); //--> "Value is 3.55" 
相关问题