2017-04-12 30 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" 
相關問題