Teknisk > Generelt teknisk

Powershell: Round to nearest integer

(1/1)

Floyd-ATC:
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: ---function round( $value, [MidpointRounding]$mode = 'AwayFromZero' ) {
  [Math]::Round( $value, $mode )
}
--- Slutt kode ---



--- Kode: ---PS> [int]3.5
4
PS> [int]4.5
4
PS> round 3.5
4
PS> round 4.5
5
--- Slutt kode ---

Navigering

[0] Oversikt

Skift til full visning