![](/img/trans.png)
[英]How can I format currency with no decimals but only when the decimal is zero?
[英]How can I return only two decimals when multiplying numbers?
我必須將兩個小數相乘: 6,0 * 5,50
,結果是: 33,000
如何將結果的最后0
截掉? 我想要的結果是33,00
。
要相乘,我使用查詢:
var rr = (from s in baza.customer
where userID == s.userID
&& s.data.Month == dat
select s.hours * s.prise.Sum();
您有一個字符集問題。 您的代碼在北美語言環境中運行,其中,
是千位分隔符(而.
是小數點)。
似乎這里有些混亂,我將向其他兩個人發布類似的答案,但其中包含簡短但完整的程序以說明為什么這樣做是必要的。
首先,有必要澄清一下(如注釋所示),這是將兩個小於10的數字相乘-作為C#文字,它們分別是6.0m和5.50m。 它們是decimal
值的事實也很相關-因為decimal
保持尾隨零,而double
精度則不然。 所以:
// Note: my system is in en-gb
using System;
class Test
{
static void Main()
{
decimal x = 6.0m;
decimal y = 5.50m;
decimal z = x * y;
Console.WriteLine(z); // Prints 33.000
Console.WriteLine(z.ToString("0.00")); // Prints 33.00
// Same with composite formatting
Console.WriteLine("{0:0.00}", z); // Still prints 33.00
// If you want fewer than 2 decimal digits when they're
// not necessary
Console.WriteLine(z.ToString("0.##")); // Prints 33
}
}
如果當前線程的區域性使用','
而不是'.'
作為小數點分隔符,那么您顯然會得到“ 33,00”。
如果要將實際值四舍五入到小數點后兩位,則可以使用decimal.Round
:
decimal rounded = decimal.Round(z, 2);
但是,這當然會丟失大量信息。
請注意,通常只在要向用戶展示信息時才應用字符串格式。
嘗試使用字符串格式設置: string.Format("{0:0.##}", number)
。
為什么不在輸出時格式化值,而不是嘗試在計算時減少小數位?
采用
String.Format("{0:0.##}", number)
要么
String.Format("{0:0.00}", number)
在輸出中僅保留小數位
NumberFormat nf4 = new DecimalFormat("0000");
var rr=+nf6.format(new Integer(rr));
假設您要使用字符串形式的表示形式,則需要使用“ 標准數字格式字符串”來格式化結果。 例如,在對您發布的值(33.000)進行快速測試之后,代碼(33.000).ToString("f")
得到的結果為33.00。
注意:“ f”可能不是您所需的實際格式說明符-最好通讀我首先鏈接的文章。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.