Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我怎样才能在一个小数值中得到不多于或不少于两个小数位?_C#_Excel_Decimal_Excel Interop_Decimal Precision - Fatal编程技术网

C# 我怎样才能在一个小数值中得到不多于或不少于两个小数位?

C# 我怎样才能在一个小数值中得到不多于或不少于两个小数位?,c#,excel,decimal,excel-interop,decimal-precision,C#,Excel,Decimal,Excel Interop,Decimal Precision,使用此代码: totalPriceCell.Value2 = TotalPrice; totalPriceCell.Value2 = TotalPrice.ToString("#.##"); …我得到的值是“3.14963245”,我想改为“3.15” 所以我用了这个代码: totalPriceCell.Value2 = TotalPrice; totalPriceCell.Value2 = TotalPrice.ToString("#.##"); …这确实解决了这个问题,但我仍然得到诸

使用此代码:

totalPriceCell.Value2 = TotalPrice;
totalPriceCell.Value2 = TotalPrice.ToString("#.##");
…我得到的值是“3.14963245”,我想改为“3.15”

所以我用了这个代码:

totalPriceCell.Value2 = TotalPrice;
totalPriceCell.Value2 = TotalPrice.ToString("#.##");
…这确实解决了这个问题,但我仍然得到诸如“7.6”和“35”之类的值(我希望是“7.60”和“35.00”)

除了为VAL(如“7.6”)手动添加“0”和为值(如“35”)手动添加“.00”之外,我还能做些什么来实现这一点

更新 尼瑟的建议奏效了,但这两个建议都没有:

totalPriceCell.Value2 = TotalPrice.ToString("F2");
……这也不是:

totalPriceCell.Value2 = Math.Round(TotalPrice, 2).ToString("F2");
我仍然得到“7.6”等:

更新2 这是一个Excel问题,因为当我添加以下内容时:

MessageBox.Show(Math.Round(TotalPrice, 2).ToString("F2"));
…我确实看到了诸如“7.60”(而不是“7.6”)之类的值


您可以改用#.00格式。

看起来您试图将数字四舍五入到小数点后2位,然后输出尾随0的答案

只需使用
Math.Round()
函数进行取整,然后使用
.ToString(“F2”)
格式显示:

totalPriceCell.Value2 = Math.Round(TotalPrice, 2).ToString("F2");

Math.Round(arg1,arg2)
:其中第一个参数(arg1)是要舍入的值,第二个参数(arg2)是要舍入的小数位数

.ToString(“F2”)
:使用指定的“定点”格式的
“F2”
-F;2为小数点后的位数


希望这有帮助:)

因为它是Excel,所以我必须准确地告诉范围/单元格如何操作,如下所示:

totalPriceCell.NumberFormat = "#,##0.00";

会员5年多了,仍然问得很差,研究缺乏问题……那么,你想把你的值四舍五入到小数点后2位吗?为什么不直接使用
Math.Round(value,2)
函数,然后使用
.ToString(“F2”)
函数呢?看看这篇文章:。你可以;但从我所知道的来看,OP也希望对数字进行四舍五入,tooI仍然存在问题,但这显然是Excel显示问题。@B.ClayShannon——啊,对——听到这个消息很遗憾——很好的Excel。从您最初的问题开始,直到您刚刚更新它,才100%清楚您正在使用Excel。快乐编码!:)