Menu
CoddyTech

Numbers And Math

Part of the PowerShell Basics section of Coddy's PowerShell journey. Lesson 7 of 28.

PowerShell numbers are whole numbers ([int], such as 42) or decimals ([double], such as 4.5). The operators are +, -, *, / and %, the remainder of a division.

/ keeps the decimal part, so 7 / 2 is 3.5. For whole units, round down with [math]::Floor():

$eggs = 26
Write-Output ([math]::Floor($eggs / 12))
Write-Output ($eggs % 12)
Write-Output ([math]::Round(2 / 3, 2))
2
2
0.67

26 eggs fill 2 boxes of 12, with 2 eggs left. [math]::Round(x, 2) keeps 2 decimals.

Turning a decimal into an [int] rounds it, it does not cut it: [int](26 / 12) is 2, but [int](23 / 12) is 2 as well, because 1.92 rounds up. Use [math]::Floor() when you need the whole part.

$x += 5 is short for $x = $x + 5, and $x++ adds 1.

challenge icon

Challenge

Easy

A video lasts 5999 seconds. Turn that into hours, minutes and seconds.

  1. Store 5999 in $totalSeconds.
  2. Print Hours: followed by the whole hours.
  3. Print Minutes: followed by the whole minutes left after the hours.
  4. Print Seconds: followed by the seconds left after the minutes.

Round down with [math]::Floor(): 5999 / 3600 is 1.67, which is 1 whole hour.

Your script prints:

Hours: 1
Minutes: 39
Seconds: 59

Try it yourself

$totalSeconds = 5999
# Print the hours, minutes and seconds
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in PowerShell Basics