Immutable Money
Completed
Create an immutable class Money holding an amount in cents (long) with methods plus, times(int) returning new objects, and toString like 12.05. Read prices and quantities and print the order total.
Input
n, then n lines price qty (price with 2 decimals).
Output
The total.
Example
Input
3 0.10 3 19.99 2 5 1
Output
45.28
Editor
Java
Hints
Store money as whole cents to avoid floating-point rounding errors.
Immutable: fields are final and methods return new objects.
Solution explanation
0.1 + 0.2 is not exactly 0.3 in floating point; counting cents with long keeps money exact.
Show solution
import java.util.Scanner;
final class Money {
private final long cents;
Money(long cents) {
this.cents = cents;
}
static Money parse(String text) {
String[] p = text.split("\\.");
long whole = Long.parseLong(p[0]);
long frac = p.length > 1 ? Long.parseLong((p[1] + "00").substring(0, 2)) : 0;
return new Money(whole * 100 + frac);
}
Money plus(Money other) {
return new Money(cents + other.cents);
}
Money times(int qty) {
return new Money(cents * qty);
}
@Override
public String toString() {
return String.format("%d.%02d", cents / 100, cents % 100);
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Money total = new Money(0);
for (int i = 0; i < n; i++) {
Money price = Money.parse(sc.next());
total = total.plus(price.times(sc.nextInt()));
}
System.out.println(total);
}
}