编写程序的时候经常遇到四舍五入的问题,以前都是使用Round函数,后来发现居然有问题,逢五的时候有时候会进位,有时候却又舍去,不知道是BUG还是其它什么问题。
今天有空的时候就来测试了一下,才发现原来也是有点规律的。
ROUND函数应该是:四舍六入、逢五时前面一位是偶数则舍、是奇数则进。以下是测试结果:
以下测试Round函数:
Round(8.104,2)=8.1
Round(8.114,2)=8.11
Round(8.124,2)=8.12
Round(8.134,2)=8.13
Round(8.144,2)=8.14
Round(8.154,2)=8.15
Round(8.164,2)=8.16
Round(8.174,2)=8.17
Round(8.184,2)=8.18
Round(8.194,2)=8.19
Round(8.105,2)=8.1
Round(8.115,2)=8.12
Round(8.125,2)=8.12
Round(8.135,2)=8.14
Round(8.145,2)=8.14
Round(8.155,2)=8.15
Round(8.165,2)=8.16
Round(8.175,2)=8.18
Round(8.185,2)=8.18
Round(8.195,2)=8.2
Round(8.106,2)=8.11
Round(8.116,2)=8.12
Round(8.126,2)=8.13
Round(8.136,2)=8.14
Round(8.146,2)=8.15
Round(8.156,2)=8.16
Round(8.166,2)=8.17
Round(8.176,2)=8.18
Round(8.186,2)=8.19
Round(8.196,2)=8.2
为此,需要四舍五入的时候还是不要用这个函数了。ASP编程使用formatnumber(8.185,2)函数,ACCESS编程则使用如下函数:
Public Function RoundToLarger(dblInput As Double, intDecimals As Integer) As Double
Dim strFormatString As String
If dblInput <> 0 Then
strFormatString = "#." & String(intDecimals, "#")
RoundToLarger = Format(dblInput, strFormatString)
Else
RoundToLarger = 0
End If
End Function