0

In my program I have a simple Coin Adding calculator. In this program at the end it displays a value of money that the coins add up to.

My issue begins here. When the currency or the double value ends up being any number where the cent value ends in a 0, it excludes it.

For example: I want it to show You have $4.50! Instead if it ends in a 0 it will print You have $4.5

How can I make it print the 0 as well. If it's something that ends in any number other than 0 it prints it.

Thanks!

fun main(){
    val Quarter1 = quarter()
    val Dime1 = dime()
    println("How many Quarters do you have?")
    var quarterQuan = readLine()!!.toDouble()
    println("How many Dimes do you have?")
    var dimeQuan = readLine()!!.toDouble()
    println("")
    println("You have {$quarterQuan} Quarters and {$dimeQuan} Dimes!")
    var quarterTotal = quarterQuan * Quarter1.quarterVal
    var dimeTotal = dimeQuan * Dime1.dimeVal
    var cashTotal:Double = quarterTotal + dimeTotal
    var roundCashTotal:Double = String.format("0%f", 
    cashTotal).toDouble() 
    //cashTotal = Float.toString()
    println("Your total cash value for change is \$ ${roundCashTotal} ")

}

class quarter{
    val quarterVal = .25

}

class dime{
    val dimeVal = .10

}

Dwild
  • 11
  • 3
  • This is not a duplicate. The problem is caused by the fact that you're formatting a Double as a String, and then turning it back to Double again! Doubles have no textual representation. You need to keep the number as a String and not convert it back to Double. – k314159 Oct 01 '21 at 13:50
  • that's not entirely true. If you print a double (which is not the best class for money, but that's another matter), it will use the default `toString` representation, as documented [here](https://docs.oracle.com/javase/8/docs/api/java/lang/Double.html#toString-double-). Basically it the number is not too big, it will print the number with least amount of decimals possible. If you want a different representation, e.g. decimal with always 2 digits, then you have to use a `NumberFormat`, and `DecimalFormat` (as suggested in the duplicate question, is one of its subclasses) – user2340612 Oct 01 '21 at 15:42
  • You don't _have_ to use `NumberFormat` or `DecimalFormat`. `String.format` is a good alternative, just make sure you know how to use it properly by reading its documentation. The format string used in the question is not right. – k314159 Oct 04 '21 at 10:02

0 Answers0