如何根据数字的最后一位四舍五入整数?
例如:
Dim x As Integer = 12
Dim y As Integer = 139
Dim z As Integer = 2322
结果应该是:
x = 20
y = 140
z = 2330
x = Math.Ceiling(x / 10.0) * 10
Module Module1
Public Function RoundUp(ByVal val As Double, ByVal pos As Integer) As Double
Dim base10 As Double = System.Math.Pow(10, pos) 'pos +: right from float point, -: left from float point.
If val > 0 Then
Return System.Math.Ceiling(val * base10) / base10
Else
Return System.Math.Floor(val * base10) / base10
End If
End Function
Sub Main()
System.Console.WriteLine(RoundUp(12, -1)) '20
System.Console.WriteLine(RoundUp(139, -1)) '140
System.Console.WriteLine(RoundUp(2322, -1)) '2330
System.Console.WriteLine(RoundUp(3.1415926, 3)) '3.142
System.Console.ReadKey()
End Sub
End Module
作为替代方案,执行此减法是一种快速方法:
x = value + ((2200000000 - value) % 10)
考虑到该值为int
(2200000000 > int.MaxValue
):