Has an EXTRA SPACE
The reason is that you're passing three arguments to Write-Host
, which the latter prints separated with spaces by default:
- Argument 1:
"The price is $"
- Argument 2:
("{0:N2}" -f ($price))
- Argument 3:
"!"
- Generally, note that in PowerShell you can not form a single string argument from directly concatenated quoted strings the way you can in
bash
, for instance, such as with "foo"'bar'
- unless the first token is unquoted, PowerShell will treat the substrings as separate arguments - see this answer.
To avoid these spaces, pass a single expandable (double-quoted) string ("..."
), which requires:
Escaping $
chars. to be used verbatim as `$
(you only got away without this in your attempt because the $
happened to be at the end of your first argument).
Enclosing the "{0:N2}" -f ($price)
expression - which can be simplified to "{0:N2}" -f $price
- in $(...)
, the 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)!"
Note:
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 this answer.
However, 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