-1

I want to write some code to determine if I need to write "Quarter" or "Quarters" depending on the amount.

Up to now I have the following code:

fun main(args: Array<String>) {
    var changeDue = 1.22;
    Change(changeDue);
}

fun Change(changeDue: Double) {
    var quarters = Math.floor(changeDue / 1.0);
    print(Math.round(quarters * 4) / 1)
    if (quarters <= 2)
        println(" Quarters")
    else if (quarters > 2)
        println(" Quarter")
    println("")
    println(".22 remain")
}

Is it correct?

Is there a better way to achieve it?

Karsten Gabriel
  • 3,115
  • 6
  • 19
Lynn
  • 1
  • 3
  • 1
    You may find it helpful to read [ask], which gives tips on how to write descriptive, non-ambiguous titles. – starball Dec 08 '22 at 04:55
  • Also please note that this code is specific to US currency and the English language. Supporting other languages and/or currencies (which most programs need to do sooner or later) would need a more sophisticated approach. – gidds Dec 08 '22 at 19:06
  • Also also please note that storing money values in floating-point fields is a [very](/questions/3730019/why-not-use-double-or-float-to-represent-currency) [bad](/questions/9142710/do-modern-floating-point-implementations-handle-exact-units-like-money-well) [idea](/questions/11870621/when-can-i-use-floating-point-types-in-java-to-do-monetary-calculations)! Especially when Kotlin has a [BigDecimal](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/java.math.-big-decimal/) type that's much more suited, and easy to use. – gidds Dec 08 '22 at 19:08

1 Answers1

0

It looks like you just have the logic backwards: it should be Quarter if quarters <= 1 and Quarters otherwise.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413