在 PowerShell 中,如何格式化屏幕输出以显示 2 位小数,如本例所示。我可以在 python 中做,但不完全是在 PowerShell 中

In PowerShell, how to format screen output for a decimal to display 2 places, like this example. I can do in python but not exactly in PowerShell

$price = 22.5

write-host "The price is $"("{0:N2}" -f ($price))"!"

#注意:打印出来-> 价格是 22.50 美元! (在 $ 之后和 ! 之前有一个 EXTRA SPACE)


我可以做这么长的路,但工作量太大了: 写主机“价格是$”-nonewline 写主机 ("{0:N2}" -f ($price)) -nonewline 写主机“!”

Has an EXTRA SPACE

原因是 您将 三个 个参数传递给 Write-Host,后者将其分开打印 默认带空格

  • 参数 1:"The price is $"
  • 参数 2:("{0:N2}" -f ($price))
  • 参数 3:"!"
  • 通常,请注意,在 PowerShell 中,您可以 而不是 从直接连接的引号字符串中形成单个字符串参数,就像在 bash 中那样,例如,例如使用 "foo"'bar' - 除非第一个标记是 未引用 ,PowerShell 会将子字符串视为 单独的参数 - 请参阅 this answer

为了避免这些空格,传递一个 single expandable (double-quoted) string ("..."),这需要:

  • 转义 $ 个字符。将 逐字 用作 `$(您只是在尝试时没有这样做,因为 $ 恰好是 最后 你的第一个参数)。

  • 包含 "{0:N2}" -f ($price) 表达式 - 可以简化为 "{0:N2}" -f $price - 在 $(...) 中,subexpression operator

# Note: No need for Write-Host, unless you explicitly want to print
#       to the *display only*.
"The price is `$$("{0:N2}" -f $price)!"

注:

  • Write-Host is typically the wrong tool to use, unless the intent is to write to the display only, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, or redirect it to a file. To output a value, use it by itself; e.g., $value instead of Write-Host $value (or use Write-Output $value, though that is rarely needed); see .

然而,Lee Dailey shows a simpler alternative using a single expression with the -f operator, whose LHS can then be a verbatim (single-quoted) string ('...'):

# If you want to use Write-Host, enclose the entire expression in (...)
'The price is ${0:N2}!' -f $price

两种选择

  1. 使用格式运算符-f
  2. 使用string.Format方法

代码

$price = 22.5

$message = "The price is `${0:N2}!" -f $price
Write-Host $message

$message = [System.String]::Format("The price is `${0:N2}!", @($price))
Write-Host $message

Write-Host $("The price is `${0:N2}!" -f $price)
Write-Host $([System.String]::Format("The price is `${0:N2}!", @($price)))

# //Multiple parameters
$customer = "Joma"
Write-Host $("The price is `${0:N2}!. Thanks for your purchase {1}." -f $price, $customer)
Write-Host $([System.String]::Format("The price is `${0:N2}!. Thanks for your purchase {1}.", @($price, "Joma")))

输出