Bird
0
0

You want to format a list of product prices to show as currency with 2 decimals using the -f operator inside a loop. Which code snippet correctly formats each price stored in $prices array?

hard📝 Application Q15 of 15
PowerShell - String Operations
You want to format a list of product prices to show as currency with 2 decimals using the -f operator inside a loop. Which code snippet correctly formats each price stored in $prices array?
Aforeach ($p in $prices) { "Price: $p:C2" }
Bforeach ($p in $prices) { "Price: {0:C2}" -f $p }
Cforeach ($p in $prices) { "Price: {1:C2}" -f $p }
Dforeach ($p in $prices) { "Price: {0:C}" -f $prices }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the currency format specifier

    The format specifier 'C2' formats a number as currency with 2 decimal places.
  2. Step 2: Check loop and placeholder usage

    foreach ($p in $prices) { "Price: {0:C2}" -f $p } correctly loops over each price $p and formats it with {0:C2} and passes $p as argument. foreach ($p in $prices) { "Price: $p:C2" } incorrectly tries to format inside string without -f. foreach ($p in $prices) { "Price: {1:C2}" -f $p } uses {1:C2} but only one argument is passed, causing error. foreach ($p in $prices) { "Price: {0:C}" -f $prices } passes entire array $prices instead of single price.
  3. Final Answer:

    foreach ($p in $prices) { "Price: {0:C2}" -f $p } -> Option B
  4. Quick Check:

    Loop each price with {0:C2} and $p argument = A [OK]
Quick Trick: Use {0:C2} with single variable inside loop [OK]
Common Mistakes:
  • Using wrong placeholder index
  • Passing whole array instead of single item
  • Trying to format without -f operator

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes