在VB.NET中防止Math.Round(95.55555555,2)从四舍五入到95.56

时间:2011-03-30 16:00:00

标签: vb.net

如果我在VB.NET中Math.Round(95.55555555,2),结果是95.56,但我希望结果为95.55。有没有办法在VB.NET中执行此操作?我想我只想保留小数位,但不要围绕它们

6 个答案:

答案 0 :(得分:7)

看起来像Math.Truncate(95.5555555 * 100) / 100
Truncate Decimal number not Round Off

答案 1 :(得分:5)

尝试使用Math.Floor(95.55555555 * 100) / 100

或者,如果要舍入到特定的小数位数:

Public Function RoundDown(ByVal value As Double, ByVal decimalPlaces As Integer) As Double
    If (decimalPlaces < 1) Then
        Throw New ArgumentException("Invalid decimalPlaces: less than 1")
    EndIf

    Dim factor As Integer = 10 ^ decimalPlaces
    Return Math.Floor(value * factor) / factor
End Sub

答案 2 :(得分:2)

有几种方法可以做到这一点。一个是从数字中减去0.05,然后使用Math.Round(number, 2)。 (当你拥有floor时,这与实施ceilinground函数的原理相同。)

更好的方法可能是

Math.Truncate(number * 100) / 100

只是将数字乘以100并截断它,给出一个带有所需数字的整数值,然后除以100将其变回小数。

答案 3 :(得分:1)

你不需要Math.Round。你想要Math.Truncate。

Dim decimalNumber As Double = 95.55555555
Dim truncatedNumber As Double = Math.Truncate(decimalNumber * 100) / 100

您的结果将是95.55。

答案 4 :(得分:0)

您可以使用:

static double TruncateWithDecimals(double n, int nOfDec)
        {
           return Math.Round(Math.Floor(n * Math.Pow(10, nOfDec)) /  Math.Pow(10, nOfDec), nOfDec);
        }
抱歉,这是C#,但你可以很容易地猜到如何在vb中翻译。

答案 5 :(得分:0)

Public Function Round(Number As Decimal, places As Integer) As Decimal
    'Convert number to string
    Dim NumberString As String = Number.ToString
    'Check if the number contains a decimal, if not return the number
    If NumberString.IndexOf("."c) = -1 Then Return Number
    'Get the whole number part of the string
    Dim IntegerPart As String = NumberString.Split("."c)(0)
    'Get the Decimal part of the string
    Dim DecimalPart As String = NumberString.Split("."c)(1)
    'If the number is already rounded to n decimal places, then return the number
    If DecimalPart.Length = places Then Return Number
    'Get whichever decimals are being rounded to
    Dim ToPlacePart As String = DecimalPart.Substring(0, places)
    'get the other part that will be compared
    Dim ComparePart As String = DecimalPart.Substring(places)
    'Create a midpoint to compare the compare part to
    Dim ControlMidPoint As Decimal = Decimal.Parse("1" & Replace(Space(ComparePart.Length), Space(1), "0")) / 2
    'Create the base result(Add the integer part to the decimal part that will stay)
    Dim Result As Decimal = Decimal.Parse(IntegerPart & "." & ToPlacePart)
    'Create an increment to add if the comparepart is greater than the mid point(ex 0.001, 0.01, 0.0000001)
    Dim AddNum As Decimal = Decimal.Parse("0." & Replace(Space(ToPlacePart.Count - 1), Space(1), "0") & "1")
    'If the comparepart was equal to or greater than the midpoint, then add the addpart to the base result and return it
    If Decimal.Parse(ComparePart) >= ControlMidPoint Then Return Result + AddNum
    'Just return the base result, because the compare part was smaller than the midpoint
    Return Result
End Function
相关问题