Home > other >  How to add Trailing Zeros to an Int in Scala?
How to add Trailing Zeros to an Int in Scala?

Time:10-07

I'm making a program in Scala that asks the user a few questions and then depending on which responses they give, it comes back with an amount of money they owe. I am wondering how to make it so that the Int for cents always has a second digit. For example, if the person owes $7.20, then my program will say $7.2. How do I make it so that there is always a zero in that second spot? I believe this can be done with f interpolation but I'm not sure. Here is my working code.

Basically (I think) the question lies in that final line and how to add the zero.

(If anyone wants to run it and see what I'm talking about, input no, yes, yes)

import scala.io.StdIn._
println("Would you like a sandwich? Yes/No")
val sandAnswer = (readLine()).toLowerCase
println("Would you like a drink? Yes/No")
val drinkAnswer = (readLine()).toLowerCase
var loyAnswer = "Hello"
if ((drinkAnswer == "yes") || (sandAnswer == "yes")) {
  println("Are you a member of our loyalty program? Yes/No")
  loyAnswer = (readLine()).toLowerCase
}
var pricecents = 0
if (sandAnswer == "yes") {
  pricecents  = 825
}
if (drinkAnswer == "yes") {
  pricecents  = 225
}
if (loyAnswer == "yes") {
  pricecents -= pricecents / 10
}
val dollars = pricecents / 100
val cents = pricecents % 100
println(f"Your total is $$$dollars.$cents")

CodePudding user response:

Yes, you can do it with f interploator. For example,

val money = 7.2

f"$money%.2f"   // ===> 7.20

CodePudding user response:

First convert the integer to a String, then use padTo on the String:

2.toString.padTo(2, '0') == "20"
3.toString.padTo(10, '0') == "3000000000"

so, in your case, something like

f"Your total is $$$dollars.${cents.toString.padTo(2, '0')}"
  • Related