2014-04-29 111 views
1

我想說明的雙重價值標籤(C#)有2位小數不事項看重像13或13.5或13.505 它總是顯示13.00數爲String(始終爲2位小數)

+4

那麼你到目前爲止嘗試過什麼?你能舉一個簡短但完整的例子嗎? –

+0

什麼是預期產量13.00? –

+0

是啊..預計輸出是13.00 –

回答

9

可以傳遞到到字符串的方法格式

如:

ToString("0.00"); //2dp Number 

ToString("n2"); // 2dp Number 

ToString("c2"); // 2dp currency 

http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

要改變,例如,13.505到13.00你'd也想通過Math.Floor運行它,或者使用其他建議的方法之一進行舍入。

Math.Floor(value) 

http://msdn.microsoft.com/en-us/library/e0b5f0xb.aspx

如果,另一方面,你要改變13.505至13.50你想通過Math.Truncate運行它。

Math.Truncate(Value) 

http://msdn.microsoft.com/en-us/library/7d101hyf(v=vs.110).aspx

所以綁一起:

Double testValue = 13.505; 
Double testValueTruncated = Math.Truncate(100 * testValue)/100; 
string withDecimalPlaces = testValueTruncated.ToString("0.00"); 

withDecimalPlaces現在將有值 「13.50」

+0

這是行不通的 –

+0

我添加了一個例子。它以什麼方式不起作用? – Murphy

+0

在13.505中,輸出必須是13.50,而不是13.00 13.00只在那些值類似13或13.0的情況下 如果13.1輸出將是13.10。我希望,現在一切都清楚了。 –

0

試試這個方法

double i=12.22222;    //first variable 
double j=1.2545;    //second variable 
double h=i*j;     // multiple first and second 
string s=h.ToString("0.00"); // convert to string and proper format  

這個方法返回

s="15.33" 
+0

但是,如果h的值是15,那麼我想要15.00作爲輸出 –

+0

然後你加這也string [] st = s.Split('。'); (st.Length> 0) { s = s; } else { s = s +「.00」; } – Manoj