【问题标题】:Can anyone help me to get math.round() to get the following output谁能帮我得到 math.round() 以获得以下输出
【发布时间】:2015-07-19 14:40:13
【问题描述】:

DecimalValue = (Math.Round(varDecimal /8, 1)

'varDecimal' 的值会不断变化,但在小数点后的输出中我只需要 #.0 或 #.5

例如

9/8 =1.1 --> 但我需要这个 1.5
11/8 =1.4 --> 但我需要这个 1.5
21/8 =2.6 --> 但我需要这个 3.0
27/8 =3.4 --> 但我需要这个 3.5
33/8 =4.1 --> 但我需要这个 4.5
39/8 =4.9 --> 但我需要这个 5.0
45/8 =5.6 --> 但我需要这个 6.0

这个想法是小数点后0以上应该四舍五入到0.5和0.5以上应该四舍五入1

【问题讨论】:

  • 使用Decimal.Round它会产生你所需要的。

标签: .net vb.net rounding


【解决方案1】:

这是它在 C# 中的样子,但应该很容易移植到 VB.Net:

http://goo.gl/ztLJC2

Math.Ceiling((double)value * 2) / 2 

【讨论】:

    【解决方案2】:

    你可以试试这个小方法。

    Public Function Round(num As Double) As Double
        Dim intVal =  CInt(Math.Truncate(num))
        Dim remainder = num - intVal
    
        If remainder = 0 Then
            Return num
    
        ElseIf remainder <= 0.5 Then
    
            remainder = 0.5
    
    
            Return (intVal + remainder)
        Else
    
    
            intVal += 1
    
    
            Return CDbl(intVal)
        End If
    
    End Function
    

    【讨论】:

    • 你的函数结果为6.5正在计算45/8
    • @nelek 我在 c# 版本中获得了 6 ... 不确定是否可以不同
    • 你的 intVal=Cint(num) 返回 6 而不是 5 ...函数已经舍入到一个大整数,因为结果是 5.625
    • @nelek 我已经看到了这个问题 .. 已修复。谢谢。在您指出之前并没有真正在 vb.net 中进行测试:)
    • 没有问题。提供您的解决方案来解决这个问题是不公平的;)
    【解决方案3】:

    使用Math.Ceiling()

    Math.Ceiling(value)
    //Do your computations to get the .5
    

    https://msdn.microsoft.com/en-us/library/zx4t0t48(v=vs.110).aspx

    【讨论】:

      【解决方案4】:

      这应该有效:math.round((value*2)+0.5)/2)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-14
        • 2021-02-03
        • 2014-05-09
        • 1970-01-01
        • 1970-01-01
        • 2012-11-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多