Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))"!"

#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 "!"

like image 940
Korgon Avatar asked Oct 24 '25 08:10

Korgon


1 Answers

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
like image 83
mklement0 Avatar answered Oct 26 '25 03:10

mklement0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!