6

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.

2
  • 2
    the result of 115/10 would be a double in powershell so now you need to tell us which type of rounding do you prefer to convert that double into an integer. It might be as easy as 115 / 10 -as [int] or you might need to use [Math]::Round with the MidpointRounding overload. Commented Nov 23, 2023 at 3:16
  • 1
    Read up on About_Arthmetic_operators. It will show you how to get rounding behavior that's diffferent from the powershell default. Commented Nov 23, 2023 at 3:27

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.