$price = 22.5
write-host "The price is $"("{0:N2}" -f ($price))"!"
#NOTE: Prints out-> The price is $ 22.50 ! (Has an EXTRA SPACE after the $ & before the !)
I can do it this long way, but it is too much work: write-host "The price is $" -nonewline write-host ("{0:N2}" -f ($price)) -nonewline write-host "!"
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:
"The price is $"("{0:N2}" -f ($price))"!"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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With