Tehc
Tehc

Reputation: 689

How to correctly round numbers in PowerShell

As the title suggest i'm expiriencing some issues with rounding numbers. My Script currently looks like this:

[uint16]$Product1 = Read-Host "Enter the price of your product: "
...
#$TotalProducts contains the Value from all products together
Write-Host "You spent an amount of $TotalProducts for todays shopping."

I want the programm to round the numbers so the total isn't some ridiculous long number. It does work but after i calculated it manually i saw that the programm calculated something else.

The problem here is that the programm rounds for example 122.50 to 122 instead of 123.

I tried using the following syntax but without success:

[math]::Round($Product1)[System.Midpoint.Rounding]::AwayFromZero) = Read-Host "Enter the price of your product: "

Am i trying the right thing but i'm butchering the syntax or am i completly wrong with this approach?

Upvotes: 3

Views: 8193

Answers (1)

Jonas Andersen
Jonas Andersen

Reputation: 489

Read-Host returns a string.

You should read first, then round the number.

$Product1 = Read-Host "Enter the price of your product: "
$RoundedNumber = [math]::Round($Product1, [System.MidpointRounding]::AwayFromZero)

You now have your rounded value in $RoundedNumber.

Upvotes: 5

Related Questions