Skip to content
AgileLogics
4 min read

Numbers and Math

Prerequisites: Data types

7 + 2
7 - 2
7 * 2
7 / 2
7 % 2
[math]::Floor(7 / 2)
[math]::Pow(2, 10)
[math]::Round(10 / 3, 2)
[math]::Sqrt(16)
9
5
14
3.5
1
3
1024
3.33
4
  • / gives a decimal result when needed — 7 / 2 is 3.5, unlike Bash or C.
  • % gives the remainder.
  • The [math] class (from .NET) provides Round, Floor, Ceiling, Pow, Sqrt, Abs, Max, Min, and more.

Rounding: banker's rounding by default

[math]::Round(2.5)
[math]::Round(3.5)
[math]::Round(2.5, [MidpointRounding]::AwayFromZero)
2
4
3

.NET rounds halves to the nearest even number by default ("banker's rounding"). For the school-style rounding most people expect, pass AwayFromZero.

Size suffixes

1KB
1MB
5GB / 1MB
$bytes = 3456789
'{0:N1} MB' -f ($bytes / 1MB)
1024
1048576
5120
3.3 MB

KB, MB, GB, TB, and PB suffixes make file-size arithmetic easy.

Money: use decimal

0.1 + 0.2
(0.1 + 0.2) -eq 0.3
[decimal]0.1 + [decimal]0.2
0.3
False
0.3

0.1 + 0.2 shows as 0.3, but it isn't exactly 0.3 (floating-point numbers are approximate). The [decimal] type stores exact decimal values — use it for money. (The d suffix, as in 0.1d, also creates a decimal.)

Practice

A pizza has 8 slices shared by 3 people. Print how many whole slices each person gets, how many are left over, and the exact share rounded to two decimals.

Show solution
$slices = 8
$people = 3
[math]::Floor($slices / $people)
$slices % $people
[math]::Round($slices / $people, 2)
2
2
2.67