Skrevet av Emne: Powershell: Round to nearest integer  (Lest 5538 ganger)

Utlogget Floyd-ATC

  • Livstidsdiktator
  • Administrator
  • Guru
  • *****
  • Innlegg: 542
  • Karma: +12/-0
    • MSN Messenger - floyd@atc.no
    • Vis profil
    • floyd.atc.no
    • E-post
Powershell: Round to nearest integer
« på: 14. Oktober 2016, 10:07 am »
  • [applaud]0
  • [smite]0
  • 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


    -Floyd.

    --
    Det finnes 10 typer mennesker;
    de som forstår binærtall, de som ikke gjør det, og de som forstår Grey code.