Bird
0
0

You want to create a formatted string showing a product's name left-aligned in 10 spaces and its price right-aligned in 8 spaces with 2 decimals. Which sprintf format string is correct?

hard📝 Application Q15 of 15
PHP - Output and String Handling
You want to create a formatted string showing a product's name left-aligned in 10 spaces and its price right-aligned in 8 spaces with 2 decimals. Which sprintf format string is correct?
$product = "Pen";
$price = 1.5;
$result = sprintf("...", $product, $price);
A"%-8s%-10.2f"
B"%10s%-8.2f"
C"%10s%8.2f"
D"%-10s%8.2f"
Step-by-Step Solution
Solution:
  1. Step 1: Understand alignment and width specifiers

    %-10s means left-align string in 10 spaces. %8.2f means right-align float in 8 spaces with 2 decimals.
  2. Step 2: Match requirements to options

    "%-10s%8.2f" matches left-aligned product name in 10 spaces and right-aligned price with 2 decimals in 8 spaces.
  3. Final Answer:

    "%-10s%8.2f" -> Option D
  4. Quick Check:

    %-10s left-align string, %8.2f right-align float [OK]
Quick Trick: Use - for left-align, number for width, .N for decimals [OK]
Common Mistakes:
  • Mixing alignment flags (-) with wrong specifier
  • Swapping width numbers for string and float
  • Forgetting .2 for decimal precision on float

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes