# PowerTip: Use PowerShell to Round Numbers

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

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?

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

1. Chen V says:

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

2. Chen V says:

[math]::Truncate(22/7) does the same job ðŸ™‚

3. thank you

4. MNscripter says:

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

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

6. Chen V says:

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

7. 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 ðŸ™‚

8. Gerry says:

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

9. Gerry says:

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

10. 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

11. ian_pick says:

Nice one, it worked a treat.

12. David says:

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