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.6726 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
EasyA video lasts 5999 seconds. Turn that into hours, minutes and seconds.
- Store
5999in$totalSeconds. - Print
Hours:followed by the whole hours. - Print
Minutes:followed by the whole minutes left after the hours. - 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: 59Try it yourself
$totalSeconds = 5999
# Print the hours, minutes and seconds
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PowerShell Basics
5Project: Password Checker
Project OverviewLength Check