0
help tying to call method to count change
I created a method (quarters) when I pass any Double value (changeDue) into the method I want to know the exact number of quarters there are as well as partial change returned example quarters (10.22) Answer: 40 quarters .22 remain fun main(args: Array<String>) { println(quarters(10.00,.22)); println(quarters(40.00)); } fun quarters(changeDue:Double):Double{ return changeDue - .75; } fun quarters(changeDue:Double,change:Double):Double{ return (changeDue - change); }
2 Answers
+ 1
To find the number of quarters, divide by its value:
quarters = total / 0.25
Since you are working with doubles, you only want to extract the integer value of that quotient:
quarters = (total / 0.25).toInt();
To get the remaining amount, subtract the value of the quarters from the total:
rem = total - 0.25 * quarters;
This will introduce some issues due to the finiteness of the double type. So, you may want to do a little "shifting the digits", to cut off the introduced error, like:
rem = (1000.0 * (total - 0.25 * quarters)).toInt() / 1000.0;
This will shift "total - 0.25 * quarters" by four digits to the left. The .toInt() call will cut off the error after the radix point, and dividing by 1000.0 shifts the result back four digits to the right.
As an alternative, you can work with a high-precision type, or cut the error using formatted output.
If you want to write a function that returns both the number of quarters and the remaining amount, then I would use a data class for that purpose. But I am not sure if you have gotten that far yet. If not, then printing the values in the "quarters" function of yours will perhaps suffice for the time being.
- 1
Thank you .I was able to come up with something. Now Im trying to find a way plurise it ..
fun main(args: Array<String>) {
var changeDue = 8.88;
var remainder = Math.round((changeDue % 0.25) * 100);
var change = quarters(changeDue);
println( "$change quarter $remainder cent remain ")
}
fun quarters(changeDue:Double):Double{
var totalchange = Math.floor(changeDue/ 0.25) ;
return totalchange
}