PowerTip: Round Number Up or Down with PowerShell


Summary: Easily use Windows PowerShell to round a number up or down.  

Hey, Scripting Guy! Question I want only a whole number returned, so I want the number rounded up or down as appropriate.
           How can I do this with Windows PowerShell?

Hey, Scripting Guy! Answer Cast the number as an integer, and Windows PowerShell will round the number up or down
           as appropriate, for example:

PS C:\> [int]22.4

22

PS C:\> [int]22.5

22

PS C:\> [int]22.6

23

Comments (6)

  1. PetSerAl says:

    It use to even rule, so [int]22.5 is 22, but [int]23.5 is 24.

  2. Erwin says:

    I’d expected [int]22.5 to be 23?

  3. Rules-Rules says:

    Rounding at midpoint is historically away from zero. Int rounding should be truncation not rounding. Net screwed this.

    PS C:scripts> [math]::Round(22.5,[System.MidpointRounding]::AwayFromZero)
    23
    PS C:scripts> [math]::Round(23.5,[System.MidpointRounding]::AwayFromZero)
    24

  4. Rules - Rules and more Rules! says:

    Yes. In grammar school they taugh this little trick.

    To "round" down just truncate:

    PS C:scripts> [math]::Truncate(22.5)
    22
    PS C:scripts> [math]::Truncate(23.5)
    23

    So "Math" calls this truncation. "Math" calls arithmetic "rounding up" "away from zero". Why?

    Look at it on the number line. The numbers line starts at zero. The midpoint belongs to the next interval.

    "even" rounding is used fro sstatistics and averaging.

    In computing we usually think we want up/down but in any cases we really want "even". Why?

    Read: http://en.wikipedia.org/wiki/Rounding

  5. Leo Jacob says:

    It uses round towards even or "Banker’s Rounding" or "Gaussian rounding" which is specified in IEEE 754 as the default. Any language following the standard will use such rounding. Mathematically speaking, it’s because it prevents positive/negative bias
    and gives more intuitive results over large distributions of numbers.

  6. James Brown says:

    Curious…

    [int]22.50000000000001
    23
    [int]22.500000000000001
    22

Skip to main content