有两位小数的Excel数字

我写了下面这个简单的代码,它把N1和N2的用户input加起来,并把它们作为输出(N3)。有一个问题是,它把每个input取整,而不是只取数。

简单的例子:N1 = 25.5,N2 = 25.5 Right Answer = 51,但它给出的答案是52.我是编程新手,所以将不胜感激任何帮助,我可以得到。

我想要它显示N3多达6个小数位,而不是四舍五入input时从N1和N2个别input。

Sub InputVariable() Dim N1 As Integer Dim N2 As Integer Dim N3 As Integer N1 = InputBox("Enter 1st number") N2 = InputBox("Enter 2nd number") N3 = N1 + N2 MsgBox ("Your total is " & N3) End Sub 

您需要使用Double数据types。 如果使用整数types( IntegerLong Integer ),则会将N1 = InputBox(...)的数字四舍五入,因为它不能在variables中存储非整数值。

编辑:双精度(8字节)相比,单精度(4字节)。 有趣的是,由于Double使用二进制数字格式,所以不能存储0.1的精确值(就像十进制不能expression1/3一样,不pipe你有多less位数)。

如果您需要使用十进制数进行精确计算,则可以使用Decimal格式。 你不能实际声明它,但你可以将一个数字转换成十进制数并将其存储在一个Variant 。 看到这个例子:

 Sub precisionTest() Dim i As Long Dim dbl As Double Dim dblResult As Double Dim dec As Variant Dim decResult As Variant dblResult = 0 decResult = 0 dbl = 0.00001 dec = CDec(0.00001) For i = 1 To 100000 dblResult = dblResult + dbl decResult = decResult + dec Next i MsgBox "Double result: " & dblResult & vbCr & "Decimal result: " & decResult End Sub 

编辑2: 舍入和格式化数字:您可以使用Formatfunction来创build您的数字string,而无需更改该值(仅用于显示目的)。 有效格式看起来像“0。##”,其中0表示小数位总是显示, #表示如果非零,则显示:

 Sub formatTest() Dim dbl As Double Dim dbl2 As Double Dim dbl3 As Double dbl = 1.234 dbl2 = 1.2 dbl3 = 0.1 MsgBox "Format(1.234,""0.##"") = " & Format(dbl, "0.##") & vbCr _ & "Format(1.234,""0.00"") = " & Format(dbl, "0.00") & vbCr _ & "Format(1.2,""0.##"") = " & Format(dbl2, "0.##") & vbCr _ & "Format(1.2,""0.00"") = " & Format(dbl2, "0.00") & vbCr _ & "Format(0.1,""#.##"") = " & Format(dbl3, "#.##") & vbCr _ & "Format(0.1,""0.00"") = " & Format(dbl3, "0.00") & vbCr End Sub 

如果你想实际上四舍五入你的数字,使用Round(number,decimalplaces)

正如InWoods提到的,你需要N1,N2和N3是双重types,那么你可以在print语句中输出结果,如下所示:

 MsgBox ("Your total is " & Format(N3, "Standard")) 

标准格式包含两位小数。