PowerTip: Use PowerShell to Round Numbers

PowerTip: Use PowerShell to Round Numbers

  • Comments 9
  • Likes

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


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


PS C:\>

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • What about rounding to a limited number of decimal places? As in financial calculations where 2 places are standard?

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

  • :) 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 :)

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

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

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

  • thank you

  • Very useful. I have used this several times!

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