Powershell - Round down to nearest whole number

后端 未结 4 1107
無奈伤痛
無奈伤痛 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:14

    [Math]::floor($x) is the built-in way to do it.

    Just be aware of how it will behave with negative numbers. [Math]::floor(5.5) returns 5, but [Math]::floor(-5.5) returns -6.

    If you need the function to return the value closest to zero, you'll need:

    If ($x -ge 0) {
        [Math]::Floor($x)
    } Else {
        [Math]::Ceiling($x)
    }
    

提交回复
热议问题