Reputation: 33
I would like to sort banknotes and coins according to an imaginary currency using strictly float variables. My code is almost finished, I only need to remove the decimals from the output. The output could be in n.00 format or, ideally, in n format. All suggestions are welcome.
Sample code:
package TEST;
import java.util.Scanner;
import java.lang.Math;
public class TEST {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//let a be currency value, r the reminder, and n the number of banknotes and coins
float a = scanner.nextFloat();
float r = a%500; float n = a/500;
//500, 100, 50, 20, 10, 5, 2 banknotes; and 0.50, 0.25, 0.10, 0.05 and 0.01 coins.
System.out.printf("Value of currency: %5.2f%n", a);
System.out.printf("Number of 500 banknotes: %5.2f%n" , n);
if (r != 0) {
a=r; r=a%100; n=a/100; System.out.printf("Number of 100 banknotes: %5.2f%n" , n);
if (r != 0) {
a=r; r=a%50; n=a/50; System.out.printf("Number of 50 banknotes: %5.2f%n" , n);
if (r != 0) {
a=r; r=a%20; n=a/20; System.out.printf("Number of 20 banknotes: %5.2f%n" , n);
if (r != 0) {
a=r; r=a%10; n=a/10; System.out.printf("Number of 10 banknotes: %5.2f%n" , n);
if (r != 0) {
a=r; r=a%5; n=a/5; System.out.printf("Number of 5 banknotes: %5.2f%n" , n);
if (r != 0) {
a=r; r=a%2; n=a/2; System.out.printf("Number of 2 banknotes: %5.2f%n" , n);
if (r != 0) {
a=r; r=a%0.50f; n=a/0.50f; System.out.printf("Number of 0.50 coins: %5.2f%n" , n);
if (r != 0) {
a=r; r=a%0.25f; n=a/0.25f; System.out.printf("Number of 0.25 coins: %5.2f%n" , n);
if (r != 0) {
a=r; r=a%0.10f; n=a/0.10f; System.out.printf("Number of 0.10 coins: %5.2f%n" , n);
if (r != 0) {
a=r; r=a%0.05f; n=a/0.05f; System.out.printf("Number of 0.05 coins: %5.2f%n" , n);
if (r != 0) {
a=r; r=a%0.02f; n=a/0.02f; System.out.printf("Number of 0.02 coins: %5.2f%n" , n);
if (r != 0) {
a=r; r=a%0.01f; n=a/0.01f; System.out.printf("Number of 0.01 coins: %5.2f%n" , n);
}}}}}}}}}}}}
}}
Sample output:
666.666
Value of currency: 666.67
Number of 500 banknotes: 1.33
Number of 100 banknotes: 1.67
Number of 50 banknotes: 1.33
Number of 20 banknotes: 0.83
Number of 10 banknotes: 1.67
Number of 5 banknotes: 1.33
Number of 2 banknotes: 0.83
Number of 0.50 coins: 3.33
Number of 0.25 coins: 0.66
Number of 0.10 coins: 1.66
Number of 0.05 coins: 1.32
Number of 0.02 coins: 0.80
Number of 0.01 coins: 1.60
Ideal output:
666.666
Value of currency: 666.67
Number of 500 banknotes: 1
Number of 100 banknotes: 1
Number of 50 banknotes: 1
Number of 20 banknotes: 0
Number of 10 banknotes: 1
Number of 5 banknotes: 1
Number of 2 banknotes: 0
Number of 0.50 coins: 3
Number of 0.25 coins: 0
Number of 0.10 coins: 1
Number of 0.05 coins: 1
Number of 0.02 coins: 0
Number of 0.01 coins: 1
Upvotes: 0
Views: 180
Reputation: 40034
Cast the float to an int.
float f = 2.65f;
int i = (int)f;
System.out.println(i);
// or
System.out.printf("%d%n", (int)f);
Prints
2
2
Upvotes: 2