mike
mike

Reputation: 35

How to align output correctly

I have the following value:

val x = List((("Burger and chips",4.99),4.99,1), (("Pasta & Chicken with Salad",8.99), 8.99,2), (("Rice & Chicken with Chips",8.99), 8.99,2))

after printing I get this:

x.foreach(x => println(x._3 + " x " + x._1 +"\t\t\t\t"+"$"+x._2 * x._3 ))

1 x (Burger and chips,4.99)             $4.99
2 x (Pasta & Chicken with Salad,8.99)               $17.98
2 x (Rice & Chicken with Chips,8.99)                $17.98

However i want this result instead:

1 x (Burger and chips,4.99)                         $4.99
2 x (Pasta & Chicken with Salad,8.99)               $17.98
2 x (Rice & Chicken with Chips,8.99)                $17.98

I know the text size is causing the problem but is there a way around it??

Thanks

Upvotes: 0

Views: 358

Answers (1)

Tzach Zohar
Tzach Zohar

Reputation: 37842

Scala's "f interpolator" is useful for this:

x.foreach { 
  case (text, price, amount) => println(f"$amount x $text%-40s $$${price*amount}") 
}

// prints:
1 x (Burger and chips,4.99)                  $4.99
2 x (Pasta & Chicken with Salad,8.99)        $17.98
2 x (Rice & Chicken with Chips,8.99)         $17.98

Upvotes: 2

Related Questions