我尝试(Decimal)0.9975
转换为string
在C#(0.##)
格式,但它舍入到1,而不是0.99
十进制转换为字符串格式化
这里是代码的数量;
decimalValue.ToString("0.##");
如何将输出写入0.99?
我尝试(Decimal)0.9975
转换为string
在C#(0.##)
格式,但它舍入到1,而不是0.99
十进制转换为字符串格式化
这里是代码的数量;
decimalValue.ToString("0.##");
如何将输出写入0.99?
我在很久很久以前就知道了。我也被类似的东西感到震惊。我欠这个帖子给他。
decimal d = 0.9975m;
decimal newDecimal = Math.Truncate((d*100))/100;
string result = string.Format("{0:N2}", newDecimal.ToString()); // OR
string result = newDecimal.ToString(); //This is simpler I guess.
希望它能帮助。
的另一种选择是接受四舍五入但是从十进制
decimal d = 0.9975m;
string result = (d-0.005m).ToString("0.##");
(0.9975 - 0.005) = 0.9925;
0.9925 => 0.99
使用格式
decimalValue.ToString("#0.0#");
的“#”将被更新减去0.005如果在占位符的值,如果'#'占位符没有值,那么这将被忽略,但'0.0'不会被忽略。
或
var value = string.Format("{0:0.00}", decimalValue);
或
decimal decimalValue = 0.9975;
value.ToString("G3");
这是因为四舍五入0.997到0.99会造成0.99至1.您可以通过尝试使用相同的代码证明了这一点。 9875。所以代码是好的,你的期望是什么错误。你需要舍入还是*截断*? –
我不建议去''0。##“',因为如果你的小数没有任何浮点值,比如'10',你会得到'”10.“',这看起来不太好在所有 – Nolonar