PowerTip: Use PowerShell to Round Numbers


Summary: Learn how to use Windows PowerShell to round numbers.

Hey, Scripting Guy! Question Is there an easy way to use Windows PowerShell to round numbers up or down in a computation that produces a large amount of numbers after the decimal point?

Hey, Scripting Guy! Answer Use the static Round method from the [math] class:

PS C:> $a = 22/7

PS C:> $a

3.14285714285714

PS C:> [math]::Round($a)

3

PS C:>

Comments (13)

  1. Chen V says:

    Using Type Casting [int][System.Math]::PI

  2. Chen V says:

    [math]::Truncate(22/7) does the same job 🙂

  3. MNscripter says:

    [math]::Floor() and [math]::ceiling() are also useful for rounding down and up, respectively, to the integer.

  4. Very useful. I have used this several times!

  5. Chen V says:

    Please ignore truncate method it’ just omitting the values after decimal not rounding up the values. My bad. Sorry !!!

  6. Chen V says:

    🙂 Other way [math]::Round(22/7) – When we are feeding inputs
    $a = 22; $b = 7; [math]::Round($a/$b) – When are not sure about the value A and B
    $var = Get-Random -Maximum 10.5 -Minimum 1.1
    ‘Original Value is: ‘ + $var
    ‘Rounded Value is: ‘ + [math]::Round($var)
    PowerShell Rocks 🙂

  7. Gerry says:

    What about rounding to a limited number of decimal places? As in financial calculations where 2 places are standard?

  8. Gerry says:

    Found it………. [math]::Round($a, 2)
    3.14

  9. dom says:

    What about rounding 100.005 to 100.01? [math]::round(100.005,2) is coming back at 100.00

    1. MKPhil says:

      This is because the Round class, by Default, rounds to the nearest even… thus
      [math]::round( 12.345 , 2 ) yields 12.34
      [math]::round( 12.355 , 2 ) yields 12.36
      [math]::round( 12.365 , 2 ) yields 12.36
      [math]::round( 12.375 , 2 ) yields 12.38

      To round 5s up, as you may have been taught in school, you need to explicitly state you are rounding “Away from zero”

      [math]::round( 12.345 , 2 , [system.midpointrounding]::AwayFromZero ) yields 12.35
      [math]::round( 12.345 , 2 , [midpointrounding]::AwayFromZero ) yields 12.35
      [math]::round( 12.345 , 2 , “AwayFromZero” ) yields 12.35
      [math]::round( 12.345 , 2 , 1 ) yields 12.35

      Source: http://www.madwithpowershell.com/2013/10/math-in-powershell.html

  10. Ian says:

    Nice one, it worked a treat.

  11. David says:

    This doesn’t work in ConstrainedLanguageMode. Exception: MethodInvocationNotSupportedInConstrainedLanguage
    What can I do to round numbers again?
    Thanks for any help

Skip to main content