在VB.NET中舍入整数

时间:2012-06-10 19:48:29

标签: vb.net algorithm numbers

如何根据数字的最后一位数对整数进行舍入?

例如:

Dim x As Integer = 12
Dim y As Integer = 139
Dim z As Integer = 2322

结果应为:

x = 20
y = 140
z = 2330

4 个答案:

答案 0 :(得分:3)

使用:

Math.Ceiling(value / 10) * 10

参考:http://msdn.microsoft.com/en-us/library/zx4t0t48.aspx#Y0

答案 1 :(得分:1)

x = Math.Ceiling(x / 10.0) * 10

答案 2 :(得分:0)

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

答案 3 :(得分:0)

作为替代方案,进行此减法是一种快速的方法:

x = value + ((2200000000 - value) % 10)

考虑到该值为int(2200000000> int.MaxValue):