Forums.ATC.no

Teknisk => Generelt teknisk => Emne startet av: Floyd-ATC på 14. Oktober 2016, 10:07 am

Tittel: Powershell: Round to nearest integer
Skrevet av: Floyd-ATC14. Oktober 2016, 10:07 am
For some bizarre reason, Microsoft decided that Powershell should by default use "Banker's rounding" which by their logic is more "natural" than what people "entrenched in C" (as well as any other programming language and elementary school level mathematics) would expect.

Long story short, Powershell will by default round both 1.5 and 2.5 to 2, 3.5 and 4.5 to 4 etc.

Workaround? Define the following function to get the universally expected "round UP from .5" behaviour:

Kode: [Velg]
function round( $value, [MidpointRounding]$mode = 'AwayFromZero' ) {
  [Math]::Round( $value, $mode )
}


Kode: [Velg]
PS> [int]3.5
4
PS> [int]4.5
4
PS> round 3.5
4
PS> round 4.5
5