如何在 PowerShell 中正确舍入数字

How to correctly round numbers in PowerShell

如标​​题所示,我遇到了一些舍入数字的问题。我的脚本目前看起来像这样:

[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."

我希望程序对数字进行四舍五入,这样总数就不会太长了。它确实有效,但在我手动计算之后,我看到程序计算了其他东西。

这里的问题是程序将 122.50 舍入到 122 而不是 123.

我尝试使用以下语法但没有成功:

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

我是在尝试正确的事情,但我在破坏语法,还是我完全错误地使用了这种方法?

Read-Host returns a string.

你应该先阅读,然后四舍五入。

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

您现在在 $RoundedNumber 中得到了舍入值。