Math.Round Metod

Definition

Avrundar ett värde till närmaste heltal eller till det angivna antalet bråksiffror.

Överlagringar

Name Description
Round(Double, Int32, MidpointRounding)

Avrundar ett flyttal med dubbel precision till ett angivet antal bråksiffror med den angivna avrundningskonventionen.

Round(Decimal, Int32, MidpointRounding)

Avrundar ett decimalvärde till ett angivet antal bråksiffror med den angivna avrundningskonventionen.

Round(Double, MidpointRounding)

Avrundar ett flyttal med dubbel precision till ett heltal med den angivna avrundningskonventionen.

Round(Double, Int32)

Avrundar ett flyttal med dubbel precision till ett angivet antal bråksiffror och avrundar mittpunktsvärden till närmaste jämna tal.

Round(Decimal, Int32)

Avrundar ett decimalvärde till ett angivet antal bråksiffror och avrundar mittpunktsvärden till närmaste jämna tal.

Round(Double)

Avrundar ett flyttal med dubbel precision till närmaste integralvärde och avrundar mittpunktsvärdena till närmaste jämna tal.

Round(Decimal)

Avrundar ett decimalvärde till närmaste integralvärde och avrundar mittpunktsvärdena till närmaste jämna tal.

Round(Decimal, MidpointRounding)

Avrundar ett decimalvärde som ett heltal med den angivna avrundningskonventionen.

Exempel

Förutom exemplen i avsnittet Kommentarer innehåller den här artikeln exempel som illustrerar följande överlagringar av Math.Round metoden:

Math.Round(Decimal)Math.Round(Double)Math.Round(Decimal, Int32)Math.Round(Decimal, MidpointRounding)Math.Round(Double, Int32)Math.Round(Double, MidpointRounding)Math.Round(Decimal, Int32, MidpointRounding)Math.Round(Double, Int32, MidpointRounding)

Kommentarer

I detta avsnitt:

Vilken metod anropar jag?

Du kan använda följande tabell för att välja en lämplig avrundningsmetod. Förutom metoderna innehåller Math.Round den Math.Ceiling även och Math.Floor.

Till Call
Avrunda ett tal till ett heltal med hjälp av avrundning till närmaste konvention. Round(Decimal)
-eller-
Round(Double)
Avrunda ett tal till ett heltal med hjälp av en angiven avrundningskonvention. Round(Decimal, MidpointRounding)
-eller-
Round(Double, MidpointRounding)
Avrunda ett tal till ett angivet antal bråksiffror med hjälp av avrundningen till närmaste konvention. Round(Decimal, Int32)
-eller-
Round(Double, Int32)
Avrunda ett tal till ett angivet antal bråksiffror med hjälp av en angiven avrundningskonvention. Round(Decimal, Int32, MidpointRounding)
-eller-
Round(Double, Int32, MidpointRounding)
Avrunda ett Single värde till ett angivet antal bråksiffror med hjälp av en angiven avrundningskonvention och minimera förlusten av precision. Single Konvertera till en Decimal och anropa Round(Decimal, Int32, MidpointRounding).
Avrunda ett tal till ett angivet antal bråktal samtidigt som du minimerar precisionsproblem vid avrundning av mittpunktsvärden. Anropa en avrundningsmetod som implementerar en jämförelse som är "större än eller ungefär lika med". Se Avrundning och precision.
Avrunda ett bråkvärde till ett heltal som är större än bråkvärdet. Till exempel avrunda 3,1 till 4. Ceiling
Avrunda ett bråkvärde till ett heltal som är mindre än bråkvärdet. Till exempel avrunda 3,9 till 3. Floor

Midpoint-värden och avrundningskonventioner

Avrundning innebär att konvertera ett numeriskt värde med en angiven precision till ett värde med mindre precision. Du kan till exempel använda Round(Double) metoden för att avrunda ett värde på 3,4 till 3,0 och Round(Double, Int32) metoden för att avrunda ett värde på 3,579 till 3,58.

I ett mittpunktsvärde är värdet efter den minst signifikanta siffran i resultatet exakt halvvägs mellan två tal. Till exempel är 3,47500 ett mittpunktsvärde om det ska avrundas till två decimaler och 7,500 är ett mittpunktsvärde om det ska avrundas till ett heltal. I dessa fall, om den avrunda till närmaste strategin används, kan det närmaste värdet inte enkelt identifieras utan en avrundningskonvention.

Metoden Round stöder två avrundningskonventioner för hantering av mittpunktsvärden:

  • Avrundning bort från noll

    Mittpunktsvärden avrundas till nästa tal bort från noll. Till exempel avrundar 3,75 till 3,8, 3,85 avrundar till 3,9, -3,75 avrundar till -3,8 och -3,85 avrundar till -3,9. Den här avrundningsformen MidpointRounding.AwayFromZero representeras av uppräkningsmedlemmen.

  • Avrundning till närmaste jämna, eller bankirens avrundning

    Mittpunktsvärden avrundas till närmaste jämna tal. Till exempel både 3,75 och 3,85 avrunda till 3,8 och både -3,75 och -3,85 runda till -3,8. Den här avrundningsformen MidpointRounding.ToEven representeras av uppräkningsmedlemmen.

Note

I .NET Core 3.0 och senare versioner finns ytterligare tre avrundningsstrategier tillgängliga via MidpointRounding uppräkning. Dessa strategier används i alla fall, inte bara för mittpunktsvärden som MidpointRounding.ToEven och MidpointRounding.AwayFromZero är.

Avrundning från noll är den mest kända formen av avrundning, medan avrundning till närmaste även är standarden i finansiella och statistiska operationer. Den överensstämmer med IEEE Standard 754, avsnitt 4. När det används i flera avrundningsåtgärder minskar avrundning till närmaste även avrundningsfelet som orsakas av konsekvent avrundning av mittpunktsvärden i en enda riktning. I vissa fall kan avrundningsfelet vara betydande.

I följande exempel visas den bias som kan uppstå vid konsekvent avrundning av mittpunktsvärden i en enda riktning. Exemplet beräknar det sanna medelvärdet för en matris med Decimal värden och beräknar sedan medelvärdet när värdena i matrisen avrundas med hjälp av de två konventionerna. I det här exemplet är det sanna medelvärdet och medelvärdet som resulterar vid avrundning till närmaste detsamma. Medelvärdet som resulterar vid avrundning från noll skiljer sig dock med 0,05 (eller med 3,6%) från det sanna medelvärdet.

decimal[] values = { 1.15m, 1.25m, 1.35m, 1.45m, 1.55m, 1.65m };
decimal sum = 0;

// Calculate true mean.
foreach (var value in values)
    sum += value;

Console.WriteLine("True mean:     {0:N2}", sum / values.Length);

// Calculate mean with rounding away from zero.
sum = 0;
foreach (var value in values)
    sum += Math.Round(value, 1, MidpointRounding.AwayFromZero);

Console.WriteLine("AwayFromZero:  {0:N2}", sum / values.Length);

// Calculate mean with rounding to nearest.
sum = 0;
foreach (var value in values)
    sum += Math.Round(value, 1, MidpointRounding.ToEven);

Console.WriteLine("ToEven:        {0:N2}", sum / values.Length);

// The example displays the following output:
//       True mean:     1.40
//       AwayFromZero:  1.45
//       ToEven:        1.40
open System

let values = [| 1.15m; 1.25m; 1.35m; 1.45m; 1.55m; 1.65m |]
let mutable sum = 0m

// Calculate true mean.
for value in values do
    sum <- sum + value

printfn $"True mean:     {sum / decimal values.Length:N2}"

// Calculate mean with rounding away from zero.
sum <- 0m
for value in values do
    sum <- sum + Math.Round(value, 1, MidpointRounding.AwayFromZero)

printfn $"AwayFromZero:  {sum / decimal values.Length:N2}"

// Calculate mean with rounding to nearest.
sum <- 0m
for value in values do
    sum <- sum + Math.Round(value, 1, MidpointRounding.ToEven)

printfn $"ToEven:        {sum / decimal values.Length:N2}"

// The example displays the following output:
//       True mean:     1.40
//       AwayFromZero:  1.45
//       ToEven:        1.40
Dim values() As Decimal = {1.15D, 1.25D, 1.35D, 1.45D, 1.55D, 1.65D}
Dim sum As Decimal

' Calculate true mean.
For Each value In values
    sum += value
Next
Console.WriteLine("True mean:     {0:N2}", sum / values.Length)

' Calculate mean with rounding away from zero.
sum = 0
For Each value In values
    sum += Math.Round(value, 1, MidpointRounding.AwayFromZero)
Next
Console.WriteLine("AwayFromZero:  {0:N2}", sum / values.Length)

' Calculate mean with rounding to nearest.
sum = 0
For Each value In values
    sum += Math.Round(value, 1, MidpointRounding.ToEven)
Next
Console.WriteLine("ToEven:        {0:N2}", sum / values.Length)

' The example displays the following output:
'       True mean:     1.40
'       AwayFromZero:  1.45
'       ToEven:        1.40

Som standard Round använder metoden avrunda till närmaste jämna konvention. I följande tabell visas överlagringarna av Round metoden och avrundningskonventionen som var och en använder.

Overload Avrundningskonvention
Round(Decimal) ToEven
Round(Double) ToEven
Round(Decimal, Int32) ToEven
Round(Double, Int32) ToEven
Round(Decimal, MidpointRounding) Bestäms av mode parameter.
Round(Double, MidpointRounding) Bestäms av mode parameter
Round(Decimal, Int32, MidpointRounding) Bestäms av mode parameter
Round(Double, Int32, MidpointRounding) Bestäms av mode parameter

Avrundning och precision

För att avgöra om en avrundningsåtgärd omfattar ett mittpunktsvärde Round multiplicerar metoden det ursprungliga värdet som ska avrundas med 10n, där n är det önskade antalet bråktalssiffror i returvärdet och avgör sedan om den återstående deldelen av värdet är större än eller lika med .5. Detta är en liten variation i ett likhetstest, och som beskrivs i avsnittet "Testning för likhet" i referensavsnittet Double är tester för likhet med flyttalsvärden problematiska på grund av flyttalsformatets problem med binär representation och precision. Det innebär att en del av ett tal som är något mindre än .5 (på grund av en precisionsförlust) inte avrundas uppåt.

I följande exempel visas problemet. Den lägger upprepade gånger till .1 till 11.0 och avrundar resultatet till närmaste heltal. 11.5 bör avrundas till 12 med hjälp av någon av midpoint-avrundningskonventionerna (ToEven eller AwayFromZero). Men som utdata från exemplet visar gör det inte det. I exemplet används "R"- standardsträngen i numeriskt format för att visa flyttalsvärdets fullständiga precision och visar att värdet som ska avrundas har förlorat precisionen vid upprepade tillägg, och dess värde är faktiskt 11,4999999999999998. Eftersom .499999999999998 är mindre än .5 spelar inte konventionerna för mellanpunktsrundning in och värdet avrundas nedåt. Som exemplet också visar uppstår inte det här problemet om du tilldelar konstantvärdet 11,5 till en Double variabel.

public static void Example()
{
    Console.WriteLine("{0,5} {1,20:R}  {2,12} {3,15}\n",
                      "Value", "Full Precision", "ToEven",
                      "AwayFromZero");
    double value = 11.1;
    for (int ctr = 0; ctr <= 5; ctr++)
        value = RoundValueAndAdd(value);

    Console.WriteLine();

    value = 11.5;
    RoundValueAndAdd(value);
}

private static double RoundValueAndAdd(double value)
{
    Console.WriteLine("{0,5:N1} {0,20:R}  {1,12} {2,15}",
                      value, Math.Round(value, MidpointRounding.ToEven),
                      Math.Round(value, MidpointRounding.AwayFromZero));
    return value + .1;
}

// The example displays the following output:
//       Value       Full Precision        ToEven    AwayFromZero
//
//        11.1                 11.1            11              11
//        11.2                 11.2            11              11
//        11.3   11.299999999999999            11              11
//        11.4   11.399999999999999            11              11
//        11.5   11.499999999999998            11              11
//        11.6   11.599999999999998            12              12
//
//        11.5                 11.5            12              12
open System

let roundValueAndAdd (value: double) =
    printfn $"{value,5:N1} {value,20:R}  {Math.Round(value, MidpointRounding.ToEven),12} {Math.Round(value, MidpointRounding.AwayFromZero),15}"
    value + 0.1

printfn "%5s %20s  %12s %15s\n" "Value" "Full Precision" "ToEven" "AwayFromZero"
let mutable value = 11.1
for _ = 0 to 5 do
    value <- roundValueAndAdd value

printfn ""

value <- 11.5
roundValueAndAdd value
|> ignore

// The example displays the following output:
//       Value       Full Precision        ToEven    AwayFromZero
//
//        11.1                 11.1            11              11
//        11.2                 11.2            11              11
//        11.3   11.299999999999999            11              11
//        11.4   11.399999999999999            11              11
//        11.5   11.499999999999998            11              11
//        11.6   11.599999999999998            12              12
//
//        11.5                 11.5            12              12
Public Sub Example()
    Dim value As Double = 11.1

    Console.WriteLine("{0,5} {1,20:R}  {2,12} {3,15}",
                    "Value", "Full Precision", "ToEven",
                    "AwayFromZero")
    Console.WriteLine()
    For ctr As Integer = 0 To 5
        value = RoundValueAndAdd(value)
    Next
    Console.WriteLine()

    value = 11.5
    RoundValueAndAdd(value)
End Sub

Private Function RoundValueAndAdd(value As Double) As Double
    Console.WriteLine("{0,5:N1} {0,20:R}  {1,12} {2,15}",
                    value, Math.Round(value, MidpointRounding.ToEven),
                    Math.Round(value, MidpointRounding.AwayFromZero))
    Return value + 0.1
End Function

' The example displays the following output:
'       Value       Full Precision        ToEven    AwayFromZero
'       
'        11.1                 11.1            11              11
'        11.2                 11.2            11              11
'        11.3   11.299999999999999            11              11
'        11.4   11.399999999999999            11              11
'        11.5   11.499999999999998            11              11
'        11.6   11.599999999999998            12              12
'       
'        11.5                 11.5            12              12

Problem med precision vid avrundning av mittpunktsvärden uppstår troligen under följande förhållanden:

I fall där bristen på precision i avrundningsåtgärder är problematisk kan du göra följande:

  • Om avrundningsåtgärden anropar en överlagring som avrundar ett Double värde kan du ändra Double till ett Decimal värde och anropa en överlagring som avrundar ett Decimal värde i stället. Decimal Även om datatypen också har problem med representation och förlust av precision är dessa problem mycket mindre vanliga.

  • Definiera en anpassad avrundningsalgoritm som utför ett "nästan lika" test för att avgöra om värdet som ska avrundas är acceptabelt nära ett mittpunktsvärde. I följande exempel definieras en RoundApproximate metod som undersöker om ett bråkvärde är tillräckligt nära ett mittpunktsvärde för att bli föremål för avrundning av mittpunkter. Som utdata från exemplet visar korrigerar det avrundningsproblem som visas i föregående exempel.

    public static void Example()
    {
        Console.WriteLine("{0,5} {1,20:R}  {2,12} {3,15}\n",
                          "Value", "Full Precision", "ToEven",
                          "AwayFromZero");
        double value = 11.1;
        for (int ctr = 0; ctr <= 5; ctr++)
            value = RoundValueAndAdd(value);
    
        Console.WriteLine();
    
        value = 11.5;
        RoundValueAndAdd(value);
    }
    
    private static double RoundValueAndAdd(double value)
    {
        const double tolerance = 8e-14;
    
        Console.WriteLine("{0,5:N1} {0,20:R}  {1,12} {2,15}",
                          value,
                          RoundApproximate(value, 0, tolerance, MidpointRounding.ToEven),
                          RoundApproximate(value, 0, tolerance, MidpointRounding.AwayFromZero));
        return value + .1;
    }
    
    private static double RoundApproximate(double dbl, int digits, double margin,
                                      MidpointRounding mode)
    {
        double fraction = dbl * Math.Pow(10, digits);
        double value = Math.Truncate(fraction);
        fraction = fraction - value;
        if (fraction == 0)
            return dbl;
    
        double tolerance = margin * dbl;
        // Determine whether this is a midpoint value.
        if ((fraction >= .5 - tolerance) & (fraction <= .5 + tolerance))
        {
            if (mode == MidpointRounding.AwayFromZero)
                return (value + 1) / Math.Pow(10, digits);
            else
               if (value % 2 != 0)
                return (value + 1) / Math.Pow(10, digits);
            else
                return value / Math.Pow(10, digits);
        }
        // Any remaining fractional value greater than .5 is not a midpoint value.
        if (fraction > .5)
            return (value + 1) / Math.Pow(10, digits);
        else
            return value / Math.Pow(10, digits);
    }
    
    // The example displays the following output:
    //       Value       Full Precision        ToEven    AwayFromZero
    //
    //        11.1                 11.1            11              11
    //        11.2                 11.2            11              11
    //        11.3   11.299999999999999            11              11
    //        11.4   11.399999999999999            11              11
    //        11.5   11.499999999999998            12              12
    //        11.6   11.599999999999998            12              12
    //
    //        11.5                 11.5            12              12
    
    open System
    
    let roundApproximate dbl digits margin mode =
        let fraction = dbl * Math.Pow(10, digits)
        let value = Math.Truncate fraction
        let fraction = fraction - value
        if fraction = 0 then
            dbl
        else
            let tolerance = margin * dbl
            // Determine whether this is a midpoint value.
            if (fraction >= 0.5 - tolerance) && (fraction <= 0.5 + tolerance) then
                if mode = MidpointRounding.AwayFromZero then
                    (value + 1.) / Math.Pow(10, digits)
                elif value % 2. <> 0 then
                    (value + 1.) / Math.Pow(10, digits)
                else
                    value / Math.Pow(10, digits)
            // Any remaining fractional value greater than .5 is not a midpoint value.
            elif fraction > 0.5 then
                (value + 1.) / Math.Pow(10, digits)
            else
                value / Math.Pow(10, digits)
    
    
    let roundValueAndAdd value =
        let tolerance = 8e-14
        let round = roundApproximate value 0 tolerance
    
        printfn $"{value,5:N1} {value,20:R}  {round MidpointRounding.ToEven,12} {round MidpointRounding.AwayFromZero,15}"
        value + 0.1
    
    printfn "%5s %20s  %12s %15s\n" "Value" "Full Precision" "ToEven" "AwayFromZero"
    let mutable value = 11.1
    for _ = 0 to 5 do
        value <- roundValueAndAdd value
    
    printfn ""
    
    value <- 11.5
    roundValueAndAdd value 
    |> ignore
    
    // The example displays the following output:
    //       Value       Full Precision        ToEven    AwayFromZero
    //
    //        11.1                 11.1            11              11
    //        11.2                 11.2            11              11
    //        11.3   11.299999999999999            11              11
    //        11.4   11.399999999999999            11              11
    //        11.5   11.499999999999998            12              12
    //        11.6   11.599999999999998            12              12
    //
    //        11.5                 11.5            12              12
    
    Public Sub Example()
        Dim value As Double = 11.1
    
        Console.WriteLine("{0,5} {1,20:R}  {2,12} {3,15}\n",
                        "Value", "Full Precision", "ToEven",
                        "AwayFromZero")
        For ctr As Integer = 0 To 5
            value = RoundValueAndAdd(value)
        Next
        Console.WriteLine()
    
        value = 11.5
        RoundValueAndAdd(value)
    End Sub
    
    Private Function RoundValueAndAdd(value As Double) As Double
        Const tolerance As Double = 0.00000000000008
        Console.WriteLine("{0,5:N1} {0,20:R}  {1,12} {2,15}",
                        value,
                        RoundApproximate(value, 0, tolerance, MidpointRounding.ToEven),
                        RoundApproximate(value, 0, tolerance, MidpointRounding.AwayFromZero))
        Return value + 0.1
    End Function
    
    Private Function RoundApproximate(dbl As Double, digits As Integer, margin As Double,
                                     mode As MidpointRounding) As Double
        Dim fraction As Double = dbl * Math.Pow(10, digits)
        Dim value As Double = Math.Truncate(fraction)
        fraction = fraction - value
        If fraction = 0 Then Return dbl
    
        Dim tolerance As Double = margin * dbl
        ' Determine whether this is a midpoint value.
        If (fraction >= 0.5 - tolerance) And (fraction <= 0.5 + tolerance) Then
            If mode = MidpointRounding.AwayFromZero Then
                Return (value + 1) / Math.Pow(10, digits)
            Else
                If value Mod 2 <> 0 Then
                    Return (value + 1) / Math.Pow(10, digits)
                Else
                    Return value / Math.Pow(10, digits)
                End If
            End If
        End If
        ' Any remaining fractional value greater than .5 is not a midpoint value.
        If fraction > 0.5 Then
            Return (value + 1) / Math.Pow(10, digits)
        Else
            Return value / Math.Pow(10, digits)
        End If
    End Function
    
    ' The example displays the following output:
    '       Value       Full Precision        ToEven    AwayFromZero
    '       
    '        11.1                 11.1            11              11
    '        11.2                 11.2            11              11
    '        11.3   11.299999999999999            11              11
    '        11.4   11.399999999999999            11              11
    '        11.5   11.499999999999998            12              12
    '        11.6   11.599999999999998            12              12
    '       
    '        11.5                 11.5            12              12
    

Avrundning och flyttal med enkel precision

Metoden Round innehåller överlagringar som accepterar argument av typen Decimal och Double. Det finns inga metoder som avrundar värden av typen Single. Om du skickar ett Single-värde till en överlagring av metoden Round omvandlas det (i C#) eller konverteras (i Visual Basic) till en Double och motsvarande Round överlagring med en Double parameter anropas. Även om det här är en bredare konvertering innebär det ofta en förlust av precision, vilket visas i följande exempel. När ett Single värde på 16,325 skickas till Round metoden och avrundas till två decimaler med hjälp av avrundningen till närmaste konvention är resultatet 16,33 och inte det förväntade resultatet på 16,32.

Single value = 16.325f;
Console.WriteLine("Widening Conversion of {0:R} (type {1}) to {2:R} (type {3}): ",
                  value, value.GetType().Name, (double)value,
                  ((double)(value)).GetType().Name);
Console.WriteLine(Math.Round(value, 2));
Console.WriteLine(Math.Round(value, 2, MidpointRounding.AwayFromZero));
Console.WriteLine();

Decimal decValue = (decimal)value;
Console.WriteLine("Cast of {0:R} (type {1}) to {2} (type {3}): ",
                  value, value.GetType().Name, decValue,
                  decValue.GetType().Name);
Console.WriteLine(Math.Round(decValue, 2));
Console.WriteLine(Math.Round(decValue, 2, MidpointRounding.AwayFromZero));

// The example displays the following output:
//    Widening Conversion of 16.325 (type Single) to 16.325000762939453 (type Double):
//    16.33
//    16.33
//
//    Cast of 16.325 (type Single) to 16.325 (type Decimal):
//    16.32
//    16.33
// In F#, 'float', 'float64', and 'double' are aliases for System.Double...
// 'float32' and 'single' are aliases for System.Single
open System

let value = 16.325f
printfn $"Widening Conversion of {value:R} (type {value.GetType().Name}) to {double value:R} (type {(double value).GetType().Name}): "
printfn $"{Math.Round(decimal value, 2)}"
printfn $"{Math.Round(decimal value, 2, MidpointRounding.AwayFromZero)}"
printfn ""

let decValue = decimal value
printfn $"Cast of {value:R} (type {value.GetType().Name}) to {decValue} (type {decValue.GetType().Name}): "
printfn $"{Math.Round(decValue, 2)}"
printfn $"{Math.Round(decValue, 2, MidpointRounding.AwayFromZero)}"

// The example displays the following output:
//    Widening Conversion of 16.325 (type Single) to 16.325000762939453 (type Double):
//    16.33
//    16.33
//
//    Cast of 16.325 (type Single) to 16.325 (type Decimal):
//    16.32
//    16.33
Dim value As Single = 16.325
Console.WriteLine("Widening Conversion of {0:R} (type {1}) to {2:R} (type {3}): ",
                value, value.GetType().Name, CDbl(value),
                CDbl(value).GetType().Name)
Console.WriteLine(Math.Round(value, 2))
Console.WriteLine(Math.Round(value, 2, MidpointRounding.AwayFromZero))
Console.WriteLine()

Dim decValue As Decimal = CDec(value)
Console.WriteLine("Cast of {0:R} (type {1}) to {2} (type {3}): ",
                value, value.GetType().Name, decValue,
                decValue.GetType().Name)
Console.WriteLine(Math.Round(decValue, 2))
Console.WriteLine(Math.Round(decValue, 2, MidpointRounding.AwayFromZero))
Console.WriteLine()

' The example displays the following output:
'    Widening Conversion of 16.325 (type Single) to 16.325000762939453 (type Double):
'    16.33
'    16.33
'    
'    Cast of 16.325 (type Single) to 16.325 (type Decimal):
'    16.32
'    16.33

Det här oväntade resultatet beror på en förlust av precision i konverteringen Single av värdet till en Double. Eftersom det resulterande Double värdet 16,325000762939453 inte är ett mittpunktsvärde och är större än 16,325 avrundas det alltid uppåt.

I många fall, som exemplet illustrerar, kan precisionsförlusten minimeras eller elimineras genom gjutning Single eller konvertering av värdet till en Decimal. Observera att eftersom det här är en begränsad konvertering krävs det att du använder en cast-operator eller anropar en konverteringsmetod.

Round(Double, Int32, MidpointRounding)

Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs

Avrundar ett flyttal med dubbel precision till ett angivet antal bråksiffror med den angivna avrundningskonventionen.

public:
 static double Round(double value, int digits, MidpointRounding mode);
public static double Round(double value, int digits, MidpointRounding mode);
static member Round : double * int * MidpointRounding -> double
Public Shared Function Round (value As Double, digits As Integer, mode As MidpointRounding) As Double

Parametrar

value
Double

Ett flyttal med dubbel precision som ska avrundas.

digits
Int32

Antalet bråktalssiffror i returvärdet.

mode
MidpointRounding

Ett av uppräkningsvärdena som anger vilken avrundningsstrategi som ska användas.

Returer

Talet som har digits bråksiffror som value avrundas till. Om value har färre bråksiffror än digitsvalue returneras oförändrat.

Undantag

digits är mindre än 0 eller större än 15.

mode är inte ett giltigt värde för MidpointRounding.

Kommentarer

Argumentets digits värde kan vara mellan 0 och 15. Det maximala antalet heltals- och bråksiffror som stöds av Double typen är 15.

Se Midpoint-värden och avrundningskonventioner för information om avrundning av tal med mittpunktsvärden.

Important

Vid avrundning av mittpunktsvärden utför avrundningsalgoritmen ett likhetstest. På grund av problem med binär representation och precision i flyttalsformatet kan det värde som returneras av metoden vara oväntat. Mer information finns i Avrundning och precision.

Om värdet för value argumentet är Double.NaNreturnerar Double.NaNmetoden . Om value är Double.PositiveInfinity eller Double.NegativeInfinityreturnerar Double.PositiveInfinity metoden respektive Double.NegativeInfinity.

Example

I följande exempel visas hur du använder Round(Double, Int32, MidpointRounding) metoden med MidpointRounding uppräkningen.


// Round a positive and a negative value using the default.
double result = Math.Round(3.45, 1);
Console.WriteLine($"{result,4} = Math.Round({3.45,5}, 1)");
result = Math.Round(-3.45, 1);
Console.WriteLine($"{result,4} = Math.Round({-3.45,5}, 1)\n");

// Round a positive value using a MidpointRounding value.
result = Math.Round(3.45, 1, MidpointRounding.ToEven);
Console.WriteLine($"{result,4} = Math.Round({3.45,5}, 1, MidpointRounding.ToEven)");
result = Math.Round(3.45, 1, MidpointRounding.AwayFromZero);
Console.WriteLine($"{result,4} = Math.Round({3.45,5}, 1, MidpointRounding.AwayFromZero)");
result = Math.Round(3.47, 1, MidpointRounding.ToZero);
Console.WriteLine($"{result,4} = Math.Round({3.47,5}, 1, MidpointRounding.ToZero)\n");

// Round a negative value using a MidpointRounding value.
result = Math.Round(-3.45, 1, MidpointRounding.ToEven);
Console.WriteLine($"{result,4} = Math.Round({-3.45,5}, 1, MidpointRounding.ToEven)");
result = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero);
Console.WriteLine($"{result,4} = Math.Round({-3.45,5}, 1, MidpointRounding.AwayFromZero)");
result = Math.Round(-3.47, 1, MidpointRounding.ToZero);
Console.WriteLine($"{result,4} = Math.Round({-3.47,5}, 1, MidpointRounding.ToZero)\n");

// The example displays the following output:

//         3.4 = Math.Round( 3.45, 1)
//         -3.4 = Math.Round(-3.45, 1)

//         3.4 = Math.Round(3.45, 1, MidpointRounding.ToEven)
//         3.5 = Math.Round(3.45, 1, MidpointRounding.AwayFromZero)
//         3.4 = Math.Round(3.47, 1, MidpointRounding.ToZero)

//         -3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
//         -3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)
//         -3.4 = Math.Round(-3.47, 1, MidpointRounding.ToZero)
// Round a positive and a negative value using the default.
let result = Math.Round(3.45, 1)
printfn $"{result,4} = Math.Round({3.45,5}, 1)"
let result = Math.Round(-3.45, 1)
printfn $"{result,4} = Math.Round({-3.45,5}, 1)\n"

// Round a positive value using a MidpointRounding value.
let result = Math.Round(3.45, 1, MidpointRounding.ToEven)
printfn $"{result,4} = Math.Round({3.45,5}, 1, MidpointRounding.ToEven)"
let result = Math.Round(3.45, 1, MidpointRounding.AwayFromZero)
printfn $"{result,4} = Math.Round({3.45,5}, 1, MidpointRounding.AwayFromZero)"
let result = Math.Round(3.47, 1, MidpointRounding.ToZero)
printfn $"{result,4} = Math.Round({3.47,5}, 1, MidpointRounding.ToZero)\n"

// Round a negative value using a MidpointRounding value.
let result = Math.Round(-3.45, 1, MidpointRounding.ToEven)
printfn $"{result,4} = Math.Round({-3.45,5}, 1, MidpointRounding.ToEven)"
let result = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)
printfn $"{result,4} = Math.Round({-3.45,5}, 1, MidpointRounding.AwayFromZero)"
let result = Math.Round(-3.47, 1, MidpointRounding.ToZero)
printfn $"{result,4} = Math.Round({-3.47,5}, 1, MidpointRounding.ToZero)\n"

// The example displays the following output:

//         3.4 = Math.Round( 3.45, 1)
//         -3.4 = Math.Round(-3.45, 1)

//         3.4 = Math.Round(3.45, 1, MidpointRounding.ToEven)
//         3.5 = Math.Round(3.45, 1, MidpointRounding.AwayFromZero)
//         3.4 = Math.Round(3.47, 1, MidpointRounding.ToZero)

//         -3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
//         -3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)
//         -3.4 = Math.Round(-3.47, 1, MidpointRounding.ToZero)
Dim posValue As Double = 3.45
Dim negValue As Double = -3.45

' Round a positive and a negative value using the default.  
Dim result As Double = Math.Round(posValue, 1)
Console.WriteLine("{0,4} = Math.Round({1,5}, 1)", result, posValue)
result = Math.Round(negValue, 1)
Console.WriteLine("{0,4} = Math.Round({1,5}, 1)", result, negValue)
Console.WriteLine()

' Round a positive value using a MidpointRounding value. 
result = Math.Round(posValue, 1, MidpointRounding.ToEven)
Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)",
                   result, posValue)
result = Math.Round(posValue, 1, MidpointRounding.AwayFromZero)
Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)",
                   result, posValue)
Console.WriteLine()

' Round a positive value using a MidpointRounding value. 
result = Math.Round(negValue, 1, MidpointRounding.ToEven)
Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)",
                    result, negValue)
result = Math.Round(negValue, 1, MidpointRounding.AwayFromZero)
Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)",
                   result, negValue)
Console.WriteLine()

'This code example produces the following results:

'  3.4 = Math.Round( 3.45, 1)
' -3.4 = Math.Round(-3.45, 1)

' 3.4 = Math.Round( 3.45, 1, MidpointRounding.ToEven)
' 3.5 = Math.Round( 3.45, 1, MidpointRounding.AwayFromZero)

' -3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
' -3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)

Anteckningar till anropare

På grund av den förlust av precision som kan uppstå genom att representera decimalvärden som flyttalsnummer eller utföra aritmetiska åtgärder på flyttalsvärden, kanske metoden i vissa fall Round(Double, Int32, MidpointRounding) inte verkar avrunda mittpunktsvärden som anges av parametern mode . Detta illustreras i följande exempel, där 2.135 avrundas till 2.13 i stället för 2.14. Detta beror på att metoden internt multipliceras value med 10siffror, och multiplikationsåtgärden i det här fallet lider av en förlust av precision.

double[] values = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 };
foreach (double value in values)
   Console.WriteLine("{0} --> {1}", value,
                     Math.Round(value, 2, MidpointRounding.AwayFromZero));

// The example displays the following output:
//       2.125 --> 2.13
//       2.135 --> 2.13
//       2.145 --> 2.15
//       3.125 --> 3.13
//       3.135 --> 3.14
//       3.145 --> 3.15
open System

let values = [| 2.125; 2.135; 2.145; 3.125; 3.135; 3.145 |]
for value in values do
    printfn $"{value} --> {Math.Round(value, 2, MidpointRounding.AwayFromZero)}"
// The example displays the following output:
//       2.125 --> 2.13
//       2.135 --> 2.13
//       2.145 --> 2.15
//       3.125 --> 3.13
//       3.135 --> 3.14
//       3.145 --> 3.15
Module Example
   Public Sub Main()
      Dim values() As Double = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 }
      For Each value As Double In values
         Console.WriteLine("{0} --> {1}", value, 
                           Math.Round(value, 2, MidpointRounding.AwayFromZero))
      Next
   End Sub
End Module
' The example displays the following output:
'       2.125 --> 2.13
'       2.135 --> 2.13
'       2.145 --> 2.15
'       3.125 --> 3.13
'       3.135 --> 3.14
'       3.145 --> 3.15

Se även

Gäller för

Round(Decimal, Int32, MidpointRounding)

Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs

Avrundar ett decimalvärde till ett angivet antal bråksiffror med den angivna avrundningskonventionen.

public:
 static System::Decimal Round(System::Decimal d, int decimals, MidpointRounding mode);
public static decimal Round(decimal d, int decimals, MidpointRounding mode);
static member Round : decimal * int * MidpointRounding -> decimal
Public Shared Function Round (d As Decimal, decimals As Integer, mode As MidpointRounding) As Decimal

Parametrar

d
Decimal

Ett decimaltal som ska avrundas.

decimals
Int32

Antalet decimaler i returvärdet.

mode
MidpointRounding

Ett av uppräkningsvärdena som anger vilken avrundningsstrategi som ska användas.

Returer

Talet med decimals bråksiffror som d avrundas till. Om d har färre bråksiffror än decimalsd returneras oförändrat.

Undantag

decimals är mindre än 0 eller större än 28.

mode är inte ett giltigt värde för MidpointRounding.

Resultatet ligger utanför intervallet för en Decimal.

Kommentarer

Se Midpoint-värden och avrundningskonventioner för information om avrundning av tal med mittpunktsvärden.

Important

Vid avrundning av mittpunktsvärden utför avrundningsalgoritmen ett likhetstest. På grund av problem med binär representation och precision i flyttalsformatet kan det värde som returneras av metoden vara oväntat. Mer information finns i Avrundning och precision.

Argumentets decimals värde kan vara mellan 0 och 28.

Example

I följande exempel visas hur du använder Round metoden med MidpointRounding uppräkningen.

decimal result;

// Round a positive value using different strategies.
// The precision of the result is 1 decimal place.

result = Math.Round(3.45m, 1, MidpointRounding.ToEven);
Console.WriteLine($"{result} = Math.Round({3.45m}, 1, MidpointRounding.ToEven)");
result = Math.Round(3.45m, 1, MidpointRounding.AwayFromZero);
Console.WriteLine($"{result} = Math.Round({3.45m}, 1, MidpointRounding.AwayFromZero)");
result = Math.Round(3.47m, 1, MidpointRounding.ToZero);
Console.WriteLine($"{result} = Math.Round({3.47m}, 1, MidpointRounding.ToZero)\n");

// Round a negative value using different strategies.
// The precision of the result is 1 decimal place.

result = Math.Round(-3.45m, 1, MidpointRounding.ToEven);
Console.WriteLine($"{result} = Math.Round({-3.45m}, 1, MidpointRounding.ToEven)");
result = Math.Round(-3.45m, 1, MidpointRounding.AwayFromZero);
Console.WriteLine($"{result} = Math.Round({-3.45m}, 1, MidpointRounding.AwayFromZero)");
result = Math.Round(-3.47m, 1, MidpointRounding.ToZero);
Console.WriteLine($"{result} = Math.Round({-3.47m}, 1, MidpointRounding.ToZero)\n");

/*
This code example produces the following results:

3.4 = Math.Round(3.45, 1, MidpointRounding.ToEven)
3.5 = Math.Round(3.45, 1, MidpointRounding.AwayFromZero)
3.4 = Math.Round(3.47, 1, MidpointRounding.ToZero)

-3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
-3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)
-3.4 = Math.Round(-3.47, 1, MidpointRounding.ToZero)
*/
// Round a positive value using different strategies.
// The precision of the result is 1 decimal place.

let result = Math.Round(3.45m, 1, MidpointRounding.ToEven)
printfn $"{result} = Math.Round({3.45m}, 1, MidpointRounding.ToEven)"
let result = Math.Round(3.45m, 1, MidpointRounding.AwayFromZero)
printfn $"{result} = Math.Round({3.45m}, 1, MidpointRounding.AwayFromZero)"
let result = Math.Round(3.47m, 1, MidpointRounding.ToZero)
printfn $"{result} = Math.Round({3.47m}, 1, MidpointRounding.ToZero)\n"

// Round a negative value using different strategies.
// The precision of the result is 1 decimal place.

let result = Math.Round(-3.45m, 1, MidpointRounding.ToEven)
printfn $"{result} = Math.Round({-3.45m}, 1, MidpointRounding.ToEven)"
let result = Math.Round(-3.45m, 1, MidpointRounding.AwayFromZero)
printfn $"{result} = Math.Round({-3.45m}, 1, MidpointRounding.AwayFromZero)"
let result = Math.Round(-3.47m, 1, MidpointRounding.ToZero)
printfn $"{result} = Math.Round({-3.47m}, 1, MidpointRounding.ToZero)\n"

// This code example produces the following results:

// 3.4 = Math.Round(3.45, 1, MidpointRounding.ToEven)
// 3.5 = Math.Round(3.45, 1, MidpointRounding.AwayFromZero)
// 3.4 = Math.Round(3.47, 1, MidpointRounding.ToZero)

// -3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
// -3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)
// -3.4 = Math.Round(-3.47, 1, MidpointRounding.ToZero)
Dim result As Decimal = 0D
Dim posValue As Decimal = 3.45D
Dim negValue As Decimal = -3.45D

' Round a positive value using different strategies.
' The precision of the result is 1 decimal place.
result = Math.Round(posValue, 1, MidpointRounding.ToEven)
Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)",
                   result, posValue)
result = Math.Round(posValue, 1, MidpointRounding.AwayFromZero)
Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)",
                   result, posValue)
result = Math.Round(posValue, 1, MidpointRounding.ToZero)
Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToZero)",
                   result, posValue)
Console.WriteLine()

' Round a negative value using different strategies.
' The precision of the result is 1 decimal place.
result = Math.Round(negValue, 1, MidpointRounding.ToEven)
Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)",
                    result, negValue)
result = Math.Round(negValue, 1, MidpointRounding.AwayFromZero)
Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)",
                   result, negValue)
result = Math.Round(negValue, 1, MidpointRounding.ToZero)
Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToZero)",
                   result, negValue)
Console.WriteLine()

'This code example produces the following results:
'
'        3.4 = Math.Round(3.45, 1, MidpointRounding.ToEven)
'        3.5 = Math.Round(3.45, 1, MidpointRounding.AwayFromZero)
'        3.4 = Math.Round(3.45, 1, MidpointRounding.ToZero)
'
'        -3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
'        -3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)
'        -3.4 = Math.Round(-3.45, 1, MidpointRounding.ToZero)
'

Se även

Gäller för

Round(Double, MidpointRounding)

Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs

Avrundar ett flyttal med dubbel precision till ett heltal med den angivna avrundningskonventionen.

public:
 static double Round(double value, MidpointRounding mode);
public static double Round(double value, MidpointRounding mode);
static member Round : double * MidpointRounding -> double
Public Shared Function Round (value As Double, mode As MidpointRounding) As Double

Parametrar

value
Double

Ett flyttal med dubbel precision som ska avrundas.

mode
MidpointRounding

Ett av uppräkningsvärdena som anger vilken avrundningsstrategi som ska användas.

Returer

Det heltal som value avrundas till. Den här metoden returnerar en Double i stället för en integrerad typ.

Undantag

mode är inte ett giltigt värde för MidpointRounding.

Kommentarer

Se Midpoint-värden och avrundningskonventioner för information om avrundning av tal med mittpunktsvärden.

Important

Vid avrundning av mittpunktsvärden utför avrundningsalgoritmen ett likhetstest. På grund av problem med binär representation och precision i flyttalsformatet kan det värde som returneras av metoden vara oväntat. Mer information finns i Avrundning och precision.

Om värdet för value argumentet är Double.NaNreturnerar Double.NaNmetoden . Om value är Double.PositiveInfinity eller Double.NegativeInfinityreturnerar Double.PositiveInfinity metoden respektive Double.NegativeInfinity.

Example

I följande exempel visas värden som returneras av Round(Double, MidpointRounding) metoden med olika mode värden.

Double[] values = { 12.0, 12.1, 12.2, 12.3, 12.4, 12.5, 12.6,
                  12.7, 12.8, 12.9, 13.0 };
Console.WriteLine($"{"Value",-10} {"Default",-10} {"ToEven",-10} {"AwayFromZero",-15} {"ToZero",-15}");

foreach (var value in values)
    Console.WriteLine($"{value,-10:R} {Math.Round(value),-10} " +
        $"{Math.Round(value, MidpointRounding.ToEven),-10} " +
        $"{Math.Round(value, MidpointRounding.AwayFromZero),-15} " +
        $"{Math.Round(value, MidpointRounding.ToZero),-15}");

// The example displays the following output:
//       Value      Default    ToEven     AwayFromZero    ToZero
//       12         12         12         12              12
//       12.1       12         12         12              12
//       12.2       12         12         12              12
//       12.3       12         12         12              12
//       12.4       12         12         12              12
//       12.5       12         12         13              12
//       12.6       13         13         13              12
//       12.7       13         13         13              12
//       12.8       13         13         13              12
//       12.9       13         13         13              12
//       13         13         13         13              13
open System

let values = 
    [| 12.; 12.1; 12.2; 12.3; 12.4; 12.5
       12.6; 12.7; 12.8; 12.9; 13. |]

printfn "%-10s %-10s %-10s %-15s %-15s" "Value" "Default" "ToEven" "AwayFromZero" "ToZero"

for value in values do
    $"{value,-10:R} {Math.Round(value),-10} " +
    $"{Math.Round(value, MidpointRounding.ToEven),-10} " +
    $"{Math.Round(value, MidpointRounding.AwayFromZero),-15} " +
    $"{Math.Round(value, MidpointRounding.ToZero),-15}"
    |> printfn "%s"
    
// The example displays the following output:
//       Value      Default    ToEven     AwayFromZero    ToZero
//       12         12         12         12              12
//       12.1       12         12         12              12
//       12.2       12         12         12              12
//       12.3       12         12         12              12
//       12.4       12         12         12              12
//       12.5       12         12         13              12
//       12.6       13         13         13              12
//       12.7       13         13         13              12
//       12.8       13         13         13              12
//       12.9       13         13         13              12
//       13         13         13         13              13
Dim values() As Double = {12.0, 12.1, 12.2, 12.3, 12.4, 12.5, 12.6,
                         12.7, 12.8, 12.9, 13.0}
Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15} {4,-15}", "Value", "Default",
                "ToEven", "AwayFromZero", "ToZero")
For Each value In values
    Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15} {4,-15}",
                   value, Math.Round(value),
                   Math.Round(value, MidpointRounding.ToEven),
                   Math.Round(value, MidpointRounding.AwayFromZero),
                   Math.Round(value, MidpointRounding.ToZero))
Next

' The example displays the following output:
'       Value      Default    ToEven     AwayFromZero     ToZero
'       12         12         12         12               12
'       12.1       12         12         12               12
'       12.2       12         12         12               12
'       12.3       12         12         12               12
'       12.4       12         12         12               12
'       12.5       12         12         13               12
'       12.6       13         13         13               12
'       12.7       13         13         13               12
'       12.8       13         13         13               12
'       12.9       13         13         13               12
'       13         13         13         13               13

Anteckningar till anropare

På grund av den förlust av precision som kan uppstå genom att representera decimalvärden som flyttalsnummer eller utföra aritmetiska åtgärder på flyttalsvärden, kanske metoden i vissa fall Round(Double, MidpointRounding) inte verkar avrunda mittpunktsvärden till närmaste jämna heltal. I följande exempel, eftersom flyttalsvärdet .1 inte har någon begränsad binär representation, returnerar det första anropet Round(Double) till metoden med värdet 11,5 11 i stället för 12.

using System;

public class Example
{
   public static void Main()
   {
      double value = 11.1;
      for (int ctr = 0; ctr <= 5; ctr++)
         value = RoundValueAndAdd(value);

      Console.WriteLine();

      value = 11.5;
      RoundValueAndAdd(value);
   }

   private static double RoundValueAndAdd(double value)
   {
      Console.WriteLine("{0} --> {1}", value, Math.Round(value,
                        MidpointRounding.AwayFromZero));
      return value + .1;
   }
}
// The example displays the following output:
//       11.1 --> 11
//       11.2 --> 11
//       11.3 --> 11
//       11.4 --> 11
//       11.5 --> 11
//       11.6 --> 12
//
//       11.5 --> 12
open System

let roundValueAndAdd (value: float) =
      printfn $"{value} --> {Math.Round(value, MidpointRounding.AwayFromZero)}"
      value + 0.1

let mutable value = 11.1
for _ = 0 to 5 do
    value <- roundValueAndAdd value

printfn ""

value <- 11.5
roundValueAndAdd value
|> ignore

// The example displays the following output:
//       11.1 --> 11
//       11.2 --> 11
//       11.3 --> 11
//       11.4 --> 11
//       11.5 --> 11
//       11.6 --> 12
//
//       11.5 --> 12
Module Example
   Public Sub Main()
      Dim value As Double = 11.1
      For ctr As Integer = 0 To 5    
         value = RoundValueAndAdd(value)
      Next
      Console.WriteLine()

      value = 11.5
      RoundValueAndAdd(value)
   End Sub
   
   Private Function RoundValueAndAdd(value As Double) As Double
      Console.WriteLine("{0} --> {1}", value, Math.Round(value, 
                        MidpointRounding.AwayFromZero))
      Return value + .1
   End Function   
End Module
' The example displays the following output:
'       11.1 --> 11
'       11.2 --> 11
'       11.3 --> 11
'       11.4 --> 11
'       11.5 --> 11
'       11.6 --> 12
'       
'       11.5 --> 12

Se även

Gäller för

Round(Double, Int32)

Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs

Avrundar ett flyttal med dubbel precision till ett angivet antal bråksiffror och avrundar mittpunktsvärden till närmaste jämna tal.

public:
 static double Round(double value, int digits);
public static double Round(double value, int digits);
static member Round : double * int -> double
Public Shared Function Round (value As Double, digits As Integer) As Double

Parametrar

value
Double

Ett flyttal med dubbel precision som ska avrundas.

digits
Int32

Antalet bråktalssiffror i returvärdet.

Returer

Talet närmast value som innehåller ett antal bråktal som är digitslika med .

Undantag

digits är mindre än 0 eller större än 15.

Kommentarer

Argumentets digits värde kan vara mellan 0 och 15. Det maximala antalet heltals- och bråksiffror som stöds av Double typen är 15.

Den här metoden använder standardregeln för avrundning av MidpointRounding.ToEven. Se Midpoint-värden och avrundningskonventioner för information om avrundning av tal med mittpunktsvärden.

Important

Vid avrundning av mittpunktsvärden utför avrundningsalgoritmen ett likhetstest. På grund av problem med binär representation och precision i flyttalsformatet kan det värde som returneras av metoden vara oväntat. Mer information finns i Avrundning och precision.

Om värdet för value argumentet är Double.NaNreturnerar Double.NaNmetoden . Om value är Double.PositiveInfinity eller Double.NegativeInfinityreturnerar Double.PositiveInfinity metoden respektive Double.NegativeInfinity.

Example

I följande exempel avrundas dubbla värden med två bråktalssiffror till dubblar som har en enda bråktalssiffra.

Math.Round(3.44, 1); //Returns 3.4.
Math.Round(3.45, 1); //Returns 3.4.
Math.Round(3.46, 1); //Returns 3.5.

Math.Round(4.34, 1); // Returns 4.3
Math.Round(4.35, 1); // Returns 4.4
Math.Round(4.36, 1); // Returns 4.4
open System

printfn $"{Math.Round(3.44, 1)}" //Returns 3.4.
printfn $"{Math.Round(3.45, 1)}" //Returns 3.4.
printfn $"{Math.Round(3.46, 1)}" //Returns 3.5.

printfn $"{Math.Round(4.34, 1)}" // Returns 4.3
printfn $"{Math.Round(4.35, 1)}" // Returns 4.4
printfn $"{Math.Round(4.36, 1)}" // Returns 4.4
Math.Round(3.44, 1) 'Returns 3.4.
Math.Round(3.45, 1) 'Returns 3.4.
Math.Round(3.46, 1) 'Returns 3.5.

Math.Round(4.34, 1) ' Returns 4.3
Math.Round(4.35, 1) ' Returns 4.4
Math.Round(4.36, 1) ' Returns 4.4

Anteckningar till anropare

På grund av den förlust av precision som kan uppstå genom att representera decimalvärden som flyttal eller utföra aritmetiska åtgärder på flyttalsvärden, kanske metoden i vissa fall Round(Double, Int32) inte verkar avrunda mittpunktsvärden till närmaste jämna värde i decimalpositionen digits . Detta illustreras i följande exempel, där 2.135 avrundas till 2.13 i stället för 2.14. Detta beror på att metoden internt multipliceras value med 10siffror, och multiplikationsåtgärden i det här fallet lider av en förlust av precision.

using System;

public class Example
{
   public static void Main()
   {
      double[] values = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 };
      foreach (double value in values)
         Console.WriteLine("{0} --> {1}", value, Math.Round(value, 2));
   }
}
// The example displays the following output:
//       2.125 --> 2.12
//       2.135 --> 2.13
//       2.145 --> 2.14
//       3.125 --> 3.12
//       3.135 --> 3.14
//       3.145 --> 3.14
open System

let values = [| 2.125; 2.135; 2.145; 3.125; 3.135; 3.145 |]
for value in values do
    printfn $"{value} --> {Math.Round(value, 2)}"
// The example displays the following output:
//       2.125 --> 2.12
//       2.135 --> 2.13
//       2.145 --> 2.14
//       3.125 --> 3.12
//       3.135 --> 3.14
//       3.145 --> 3.14
Module Example
   Public Sub Main()
      Dim values() As Double = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 }
      For Each value As Double In values
         Console.WriteLine("{0} --> {1}", value, Math.Round(value, 2))
      Next
   End Sub
End Module
' The example displays the following output:
'       2.125 --> 2.12
'       2.135 --> 2.13
'       2.145 --> 2.14
'       3.125 --> 3.12
'       3.135 --> 3.14
'       3.145 --> 3.14

Se även

Gäller för

Round(Decimal, Int32)

Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs

Avrundar ett decimalvärde till ett angivet antal bråksiffror och avrundar mittpunktsvärden till närmaste jämna tal.

public:
 static System::Decimal Round(System::Decimal d, int decimals);
public static decimal Round(decimal d, int decimals);
static member Round : decimal * int -> decimal
Public Shared Function Round (d As Decimal, decimals As Integer) As Decimal

Parametrar

d
Decimal

Ett decimaltal som ska avrundas.

decimals
Int32

Antalet decimaler i returvärdet.

Returer

Talet närmast d som innehåller ett antal bråktal som är decimalslika med .

Undantag

decimals är mindre än 0 eller större än 28.

Resultatet ligger utanför intervallet för en Decimal.

Kommentarer

Argumentets decimals värde kan vara mellan 0 och 28.

Den här metoden använder standardregeln för avrundning av MidpointRounding.ToEven. Information om avrundning av tal med mittpunktsvärden finns i Midpoint-värden och avrundningskonventioner.

Important

Vid avrundning av mittpunktsvärden utför avrundningsalgoritmen ett likhetstest. På grund av problem med binär representation och precision i flyttalsformatet kan det värde som returneras av metoden vara oväntat. Mer information finns i Avrundning och precision.

Example

I följande exempel avrundas decimalvärden med två bråksiffror till värden som har en enda bråktalssiffra.

Console.WriteLine(Math.Round(3.44m, 1));
Console.WriteLine(Math.Round(3.45m, 1));
Console.WriteLine(Math.Round(3.46m, 1));
Console.WriteLine();

Console.WriteLine(Math.Round(4.34m, 1));
Console.WriteLine(Math.Round(4.35m, 1));
Console.WriteLine(Math.Round(4.36m, 1));

// The example displays the following output:
//       3.4
//       3.4
//       3.5
//
//       4.3
//       4.4
//       4.4
open System

printfn 
    $"""{Math.Round(3.44m, 1)}
{Math.Round(3.45m, 1)}
{Math.Round(3.46m, 1)}

{Math.Round(4.34m, 1)}
{Math.Round(4.35m, 1)}
{Math.Round(4.36m, 1)}"""

// The example displays the following output:
//       3.4
//       3.4
//       3.5
//
//       4.3
//       4.4
//       4.4
Console.WriteLine(Math.Round(3.44, 1))
Console.WriteLine(Math.Round(3.45, 1))
Console.WriteLine(Math.Round(3.46, 1))
Console.WriteLine()

Console.WriteLine(Math.Round(4.34, 1))
Console.WriteLine(Math.Round(4.35, 1))
Console.WriteLine(Math.Round(4.36, 1))

' The example displays the following output:
'       3.4
'       3.4
'       3.5
'       
'       4.3
'       4.4
'       4.4

Se även

Gäller för

Round(Double)

Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs

Avrundar ett flyttal med dubbel precision till närmaste integralvärde och avrundar mittpunktsvärdena till närmaste jämna tal.

public:
 static double Round(double a);
public static double Round(double a);
static member Round : double -> double
Public Shared Function Round (a As Double) As Double

Parametrar

a
Double

Ett flyttal med dubbel precision som ska avrundas.

Returer

Det närmaste aheltalet . Om bråkkomponenten a i är halvvägs mellan två heltal, varav det ena är jämnt och det andra udda, returneras det jämna talet. Observera att den här metoden returnerar en Double i stället för en integrerad typ.

Kommentarer

Den här metoden använder standardregeln för avrundning av MidpointRounding.ToEven. Information om avrundning av tal med mittpunktsvärden finns i Midpoint-värden och avrundningskonventioner.

Important

Vid avrundning av mittpunktsvärden utför avrundningsalgoritmen ett likhetstest. På grund av problem med binär representation och precision i flyttalsformatet kan det värde som returneras av metoden vara oväntat. Mer information finns i Avrundning och precision.

Om värdet för a argumentet är Double.NaNreturnerar Double.NaNmetoden . Om a är Double.PositiveInfinity eller Double.NegativeInfinityreturnerar Double.PositiveInfinity metoden respektive Double.NegativeInfinity.

Från och med Visual Basic 15.8 optimeras prestandan för dubbel-till-heltalskonvertering om du skickar värdet som returneras av metoden Round till någon av integralkonverteringsfunktionerna, eller om värdet Double som returneras av Round automatiskt konverteras till ett heltal med Option Strict inställt på Av. Den här optimeringen gör att koden kan köras snabbare – upp till dubbelt så snabbt för kod som utför ett stort antal konverteringar till heltalstyper. I följande exempel visas sådana optimerade konverteringar:

Dim d1 As Double = 1043.75133
Dim i1 As Integer = CInt(Math.Ceiling(d1))        ' Result: 1044

Dim d2 As Double = 7968.4136
Dim i2 As Integer = CInt(Math.Ceiling(d2))        ' Result: 7968

Example

I följande exempel visas avrundning till närmaste heltalsvärde.

Console.WriteLine("Classic Math.Round in CSharp");
Console.WriteLine(Math.Round(4.4)); // 4
Console.WriteLine(Math.Round(4.5)); // 4
Console.WriteLine(Math.Round(4.6)); // 5
Console.WriteLine(Math.Round(5.5)); // 6
open System

printfn "Classic Math.Round in F#"
printfn $"{Math.Round(4.4)}" // 4
printfn $"{Math.Round(4.5)}" // 4
printfn $"{Math.Round(4.6)}" // 5
printfn $"{Math.Round(5.5)}" // 6
Module Module1

    Sub Main()
    Console.WriteLine("Classic Math.Round in Visual Basic")
    Console.WriteLine(Math.Round(4.4)) ' 4
    Console.WriteLine(Math.Round(4.5)) ' 4
    Console.WriteLine(Math.Round(4.6)) ' 5
    Console.WriteLine(Math.Round(5.5)) ' 6
    End Sub

End Module

Anteckningar till anropare

På grund av den förlust av precision som kan uppstå genom att representera decimalvärden som flyttalsnummer eller utföra aritmetiska åtgärder på flyttalsvärden, kanske metoden i vissa fall Round(Double) inte verkar avrunda mittpunktsvärden till närmaste jämna heltal. I följande exempel, eftersom flyttalsvärdet .1 inte har någon begränsad binär representation, returnerar det första anropet Round(Double) till metoden med värdet 11,5 11 i stället för 12.

using System;

public class Example
{
   public static void Main()
   {
      double value = 11.1;
      for (int ctr = 0; ctr <= 5; ctr++)
         value = RoundValueAndAdd(value);

      Console.WriteLine();

      value = 11.5;
      RoundValueAndAdd(value);
   }

   private static double RoundValueAndAdd(double value)
   {
      Console.WriteLine("{0} --> {1}", value, Math.Round(value));
      return value + .1;
   }
}
// The example displays the following output:
//       11.1 --> 11
//       11.2 --> 11
//       11.3 --> 11
//       11.4 --> 11
//       11.5 --> 11
//       11.6 --> 12
//
//       11.5 --> 12
open System

let roundValueAndAdd (value: float) =
    printfn $"{value} --> {Math.Round value}"
    value + 0.1

let mutable value = 11.1

for _ = 0 to 5 do
    value <- roundValueAndAdd value

printfn ""

value <- 11.5
roundValueAndAdd value
|> ignore

// The example displays the following output:
//       11.1 --> 11
//       11.2 --> 11
//       11.3 --> 11
//       11.4 --> 11
//       11.5 --> 11
//       11.6 --> 12
//
//       11.5 --> 12
Module Example
   Public Sub Main()
      Dim value As Double = 11.1
      For ctr As Integer = 0 To 5    
         value = RoundValueAndAdd(value)
      Next
      Console.WriteLine()

      value = 11.5
      RoundValueAndAdd(value)
   End Sub
   
   Private Function RoundValueAndAdd(value As Double) As Double
      Console.WriteLine("{0} --> {1}", value, Math.Round(value))
      Return value + .1
   End Function   
End Module
' The example displays the following output:
'       11.1 --> 11
'       11.2 --> 11
'       11.3 --> 11
'       11.4 --> 11
'       11.5 --> 11
'       11.6 --> 12
'       
'       11.5 --> 12

Se även

Gäller för

Round(Decimal)

Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs

Avrundar ett decimalvärde till närmaste integralvärde och avrundar mittpunktsvärdena till närmaste jämna tal.

public:
 static System::Decimal Round(System::Decimal d);
public static decimal Round(decimal d);
static member Round : decimal -> decimal
Public Shared Function Round (d As Decimal) As Decimal

Parametrar

d
Decimal

Ett decimaltal som ska avrundas.

Returer

Heltalet närmast parametern d . Om bråkkomponenten d i är halvvägs mellan två heltal, varav det ena är jämnt och det andra udda, returneras det jämna talet. Observera att den här metoden returnerar en Decimal i stället för en integrerad typ.

Undantag

Resultatet ligger utanför intervallet för en Decimal.

Exempel

I följande exempel visas Round(Decimal) metoden. Värdet Decimal 4,5 avrundar till 4 i stället för 5, eftersom den här överlagringen använder standardkonventionen ToEven .

for (decimal value = 4.2m; value <= 4.8m; value+=.1m )
   Console.WriteLine("{0} --> {1}", value, Math.Round(value));
// The example displays the following output:
//       4.2 --> 4
//       4.3 --> 4
//       4.4 --> 4
//       4.5 --> 4
//       4.6 --> 5
//       4.7 --> 5
//       4.8 --> 5
open System

for value in 4.2m .. 0.1m .. 4.8m do
    printfn $"{value} --> {Math.Round value}"
// The example displays the following output:
//       4.2 --> 4
//       4.3 --> 4
//       4.4 --> 4
//       4.5 --> 4
//       4.6 --> 5
//       4.7 --> 5
//       4.8 --> 5
Module Example
   Public Sub Main()
      For value As Decimal = 4.2d To 4.8d Step .1d
         Console.WriteLine("{0} --> {1}", value, Math.Round(value))
      Next   
   End Sub                                                                 
End Module
' The example displays the following output:
'       4.2 --> 4
'       4.3 --> 4
'       4.4 --> 4
'       4.5 --> 4
'       4.6 --> 5
'       4.7 --> 5
'       4.8 --> 5

Kommentarer

Den här metoden använder standardregeln för avrundning av MidpointRounding.ToEven. Information om avrundning av tal med mittpunktsvärden finns i Midpoint-värden och avrundningskonventioner.

Important

Vid avrundning av mittpunktsvärden utför avrundningsalgoritmen ett likhetstest. På grund av problem med binär representation och precision i flyttalsformatet kan det värde som returneras av metoden vara oväntat. Mer information finns i Avrundning och precision.

Se även

Gäller för

Round(Decimal, MidpointRounding)

Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs
Källa:
Math.cs

Avrundar ett decimalvärde som ett heltal med den angivna avrundningskonventionen.

public:
 static System::Decimal Round(System::Decimal d, MidpointRounding mode);
public static decimal Round(decimal d, MidpointRounding mode);
static member Round : decimal * MidpointRounding -> decimal
Public Shared Function Round (d As Decimal, mode As MidpointRounding) As Decimal

Parametrar

d
Decimal

Ett decimaltal som ska avrundas.

mode
MidpointRounding

Ett av uppräkningsvärdena som anger vilken avrundningsstrategi som ska användas.

Returer

Det heltal som d avrundas till. Den här metoden returnerar en Decimal i stället för en integrerad typ.

Undantag

mode är inte ett giltigt värde för MidpointRounding.

Resultatet ligger utanför intervallet för en Decimal.

Kommentarer

Information om avrundning av tal med mittpunktsvärden finns i Midpoint-värden och avrundningskonventioner.

Important

Vid avrundning av mittpunktsvärden utför avrundningsalgoritmen ett likhetstest. På grund av problem med binär representation och precision i flyttalsformatet kan det värde som returneras av metoden vara oväntat. Mer information finns i Avrundning och precision.

Example

I följande exempel visas värden som returneras av Round(Decimal, MidpointRounding) metoden med olika mode värden.

Console.WriteLine($"{"Value",-10} {"Default",-10} {"ToEven",-10} {"AwayFromZero",-15} {"ToZero",-15}");
for (decimal value = 12.0m; value <= 13.0m; value += 0.1m)
    Console.WriteLine($"{value,-10} {Math.Round(value),-10} " +
        $"{Math.Round(value, MidpointRounding.ToEven),-10} " +
        $"{Math.Round(value, MidpointRounding.AwayFromZero),-15} " +
        $"{Math.Round(value, MidpointRounding.ToZero),-15}");

// The example displays the following output:
//       Value      Default    ToEven     AwayFromZero    ToZero
//       12.0       12         12         12              12
//       12.1       12         12         12              12
//       12.2       12         12         12              12
//       12.3       12         12         12              12
//       12.4       12         12         12              12
//       12.5       12         12         13              12
//       12.6       13         13         13              12
//       12.7       13         13         13              12
//       12.8       13         13         13              12
//       12.9       13         13         13              12
//       13.0       13         13         13              13
printfn $"""{"Value",-10} {"Default",-10} {"ToEven",-10} {"AwayFromZero",-15} {"ToZero",-15}"""
for value in 12m .. 0.1m .. 13m do
    printfn "%-10O %-10O %-10O %-15O %-15O" 
        value
        (Math.Round value)
        (Math.Round(value, MidpointRounding.ToEven))
        (Math.Round(value, MidpointRounding.AwayFromZero))
        (Math.Round(value, MidpointRounding.ToZero))

// The example displays the following output:
//       Value      Default    ToEven     AwayFromZero    ToZero
//       12.0       12         12         12              12
//       12.1       12         12         12              12
//       12.2       12         12         12              12
//       12.3       12         12         12              12
//       12.4       12         12         12              12
//       12.5       12         12         13              12
//       12.6       13         13         13              12
//       12.7       13         13         13              12
//       12.8       13         13         13              12
//       12.9       13         13         13              12
//       13.0       13         13         13              13
Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15} {4,-15}", "Value", "Default",
                "ToEven", "AwayFromZero", "ToZero")
For value As Decimal = 12D To 13D Step 0.1D
    Console.WriteLine("{0,-10} {1,-10} {2,-10} {3,-15} {4,-15}",
                   value, Math.Round(value),
                   Math.Round(value, MidpointRounding.ToEven),
                   Math.Round(value, MidpointRounding.AwayFromZero),
                   Math.Round(value, MidpointRounding.ToZero))
Next

' The example displays the following output:
'       Value      Default    ToEven     AwayFromZero     ToZero
'       12         12         12         12               12
'       12.1       12         12         12               12
'       12.2       12         12         12               12
'       12.3       12         12         12               12
'       12.4       12         12         12               12
'       12.5       12         12         13               12
'       12.6       13         13         13               12
'       12.7       13         13         13               12
'       12.8       13         13         13               12
'       12.9       13         13         13               12
'       13.0       13         13         13               13

Se även

Gäller för