Powershell - Round down to nearest whole number

后端 未结 4 1005
無奈伤痛
無奈伤痛 2021-02-05 02:20

What\'s the best way to round down to nearest whole number in Powershell?

I am trying [math]::truncate but its not giving me predictable results.

Example:

<
4条回答
  •  无人共我
    2021-02-05 03:09

    The issue you are encountering with the original 17.2/0.1 division example is due to inaccuracy in the floating-point representation of the given decimal values (as mentioned in Joey's comment on another answer). You can see this in PowerShell by examining the round-trip representation of the final value:

    PS> $bla = 17.2/0.1
    PS> $bla.GetType().FullName
    System.Double
    PS> $bla.ToString()
    172
    PS> $bla.ToString('r')
    171.99999999999997
    

    A simple way to get around this is to declare the result as int, as PowerShell will automatically round to the the result to the nearest integer value:

    PS> [int]$bli = 17.2/0.1
    PS> $bli.GetType().FullName
    System.Int32
    PS> $bli.ToString()
    172
    

    Note that this uses the default .NET method of MidpointRounding.ToEven (also known as banker's rounding). This has nice statistical properties when tabulating large numbers of numeric values, but can also be changed to the simpler away-from-zero method:

    function round( $value, [MidpointRounding]$mode = 'AwayFromZero' ) {
      [Math]::Round( $value, $mode )
    }
    
    PS> [int]3.5
    4
    PS> [int]4.5
    4
    PS> round 3.5
    4
    PS> round 4.5
    5
    

    Another option is to use a more accurate representation for the original values, which will avoid the issue entirely:

    PS> $bld = [decimal]17.2/0.1
    PS> $bld.GetType().FullName
    System.Decimal
    PS> $bld.ToString()
    172
    

提交回复
热议问题