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

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

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

thank you

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

Very useful. I have used this several times!

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

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

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)

3.14

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

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

Nice one, it worked a treat.

This doesn’t work in ConstrainedLanguageMode. Exception: MethodInvocationNotSupportedInConstrainedLanguage

What can I do to round numbers again?

Thanks for any help