如何在PowerShell中正确地四舍五入数字

3

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

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

我是在尝试正确的方法,但语法可能有误,还是我的方法完全错误了?

1个回答

5

Read-Host返回一个字符串。

应先读取数字,然后进行四舍五入。

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

现在您已经得到了 $RoundedNumber 的四舍五入值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接