我有一个PowerShell脚本,我希望它总是返回2位小数的数字(I.E 1 = 1.00,1.1 = 1.10,1.11 = 1.11) 我已经成功地为1和1.11做了,但我能想到一个不会占用1.1空间的解决方案。 多数民众赞成在我得到的东西:
$Result = $shippingprice % 2
IF ($Result -ne 1 -and $Result -ne 0)
{
$shippingpricestring = "$" + $shippingprice.ToString()
}
else {
$shippingpricestring = "$" + ($shippingprice | % { '{0:0.00}' -f $_ })
}
$Result = $itemprice % 2
IF ($Result -ne 1 -and $Result -ne 0)
{
$itempricestring = "$" + $itemprice.ToString()
}
else {
$itempricestring = "$" + ($itemprice | % { '{0:0.00}' -f $_ })
}
IF ($Result -ne 1 -and $Result -ne 0)
{
$taxstring = "$" + $tax.ToString()
}
else {
$taxstring = "$" + ($tax | % { '{0:0.00}' -f $_ })
}
$Result = $finalrice % 2
IF ($Result -ne 1 -and $Result -ne 0)
{
$finalricestring = "$" +$finalrice.ToString()
}
else {
$finalricestring = "$" + ($finalrice | % { '{0:0.00}' -f $_ })
}
答案 0 :(得分:0)
$ shippingpricestring =" $" + $ shippingprice.ToString("#。##")
脚本专家参考:Hey Scripting Guy
$shippingprice = 17.1111
$ItemPrice = 4.1211
$tax = 94.919
$finalrice =10.3211
$Result = $shippingprice % 2
IF ($Result -ne 1 -and $Result -ne 0)
{
$shippingpricestring = "$" + $shippingprice.ToString("#.##")
}
else {
$shippingpricestring = "$" + ($shippingprice | % { '{0:0.00}' -f $_ })
}
Write-Output $shippingpricestring
IF ($Result -ne 1 -and $Result -ne 0)
{
$itempricestring = "$" + $itemprice.ToString("#.##")
}
else {
$itempricestring = "$" + ($itemprice | % { '{0:0.00}' -f $_ })
}
Write-Output $itempricestring
IF ($Result -ne 1 -and $Result -ne 0)
{
$taxstring = "$" + $tax.ToString("#.##")
}
else {
$taxstring = "$" + ($tax | % { '{0:0.00}' -f $_ })
}
Write-Output $taxstring
$Result = $finalrice % 2
IF ($Result -ne 1 -and $Result -ne 0)
{
$finalricestring = "$" +$finalrice.ToString("#.##")
}
else {
$finalricestring = "$" + ($finalrice | % { '{0:0.00}' -f $_ })
}
Write-Output $finalricestring
RESULT
$17.11
$4.12
$94.92
$10.32
***以上假设所有变量都有超过2个小数位。如果说$ tax = 9.9 $ taxstring将显示为9.9而不是9.90
答案 1 :(得分:0)
如果要使用.ToString格式化数字,可以使用.ToString(格式)
实施例
$list = 1, 1.1, 1.111, 1.1111
$list | %{$_.ToString("0.00")}
输出
1.00
1.10
1.11
1.11