Integer division in PowerShell

487 views Asked by At

What is the easiest way to do integer division in PowerShell? So that the arguments are integers and the result is also an integer.

In C++ it would be e.g. 115/10.

1

There are 1 answers

0
mklement0 On BEST ANSWER

For true integer division, use System.Math.Truncate and cast the result to [int]:

[int] [Math]::Truncate(115 / 10) # -> 11

Alternatively, use System.Math.DivRem, which directly returns an [int] (or [long]):

[Math]::DivRem(115, 10, [ref] $null) # -> 11

In PowerShell (Core) 7+, additional, integer-type specific overloads are available that return tuples, so you may alternatively use:

# PowerShell 7+ only.
[Math]::DivRem(115, 10)[0] # -> 11

PowerShell widens numerical types on demand, and switches to [double] for division with integer operands (of any integer type, such as [int]) that would yield a remainder.

Casting to the result of a division to [int] (e.g. [int] (115 / 10)) is not the same as using [Math]::Truncate(), as that performs half-to-even rounding - see this answer for details.