Thursday, January 30, 2014

PowerShell - Rounding

Rounding numbers is a HUGE topic. Don't believe me? Read this:

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

So what does Powershell do? PowerShell uses what is sometimes called a 'Banker's Round', or more properly 'Round Half to Even'. This means that an expression that is exactly half way between sequential integers is rounded UP or DOWN depending on whether the integer is ODD or EVEN. I believe Microsoft chose this because it is the most common form of rounding in bookkeeping.

Of course this is best illustrated by example, run this:

[int] 1.4
[int] 1.5
[int] 1.6

It is, of course, the middle line we are really interested in. 1.5 is half way between 1 and 2. In this case [int] 1.5 resolves to 2 because the integer portion (1) is ODD. However, run this:

[int] 2.4
[int] 2.5
[int] 2.6

You will see that 2.5 is rounded DOWN to 2 because the integer portion (2) is EVEN.

So, what can you do if you don't like this behavior? You may use the .NET static 'MATH:ROUND'. There is little point in my regurgitating this here. Simple refer to:

 http://msdn.microsoft.com/en-us/library/system.math.round(v=vs.110).aspx

Happy rounding!

No comments:

Post a Comment