PowerShell:
Rounding numbers
How to:
You’ve got a few handy cmdlets and methods in PowerShell for rounding:
Round()
method from Math class
[Math]::Round(15.68) # Rounds to 16
- Specify decimals:
[Math]::Round(15.684, 2) # Rounds to 15.68
Ceiling()
andFloor()
, for always rounding up or down:
[Math]::Ceiling(15.2) # Rounds up to 16
[Math]::Floor(15.9) # Rounds down to 15
Deep Dive
Rounding numbers is no newcomer; it’s been around since ancient times, useful for trade, science, and timekeeping. Talking about PowerShell, [Math]::Round()
follows “Banker’s Rounding” by default, where 0.5s goes to the nearest even number, reducing bias in statistical operations.
You’re not just stuck with [Math]
methods though. Want more control? Check out [System.Math]::Round(Number, Digits, MidpointRounding)
where you can set how midpoints are handled: away from zero or to even (aka Banker’s Rounding).
Another angle: the System.Globalization.CultureInfo
object. It helps with locale-specific formatting and rounding preferences when dealing with international numbers.