Question: Write a new class TruncatedDollarFormat that is the same as the class DollarFormat found in Source Code folder, except that it truncates rather than rounds
Write a new class TruncatedDollarFormat that is the same as the class DollarFormat found in Source Code folder, except that it truncates rather than rounds to obtain two digits after the decimal point. When truncating, all digits after the first two are discarded, so 1.229 becomes 1.22, not 1.23. Repeat Programming Project 3 in Chapter 4 using this new class, the Project that asks for the new balance in 10 years if interest is compounded annually, monthly, and daily.
public class DollarFormat { /** Displays amount in dollars and cents notation. Rounds after two decimal places. Does not advance to the next line after output. */ public static void write(double amount) { if (amount >= 0) { System.out.print('$'); writePositive(amount); } else { double positiveAmount = -amount; System.out.print('$'); System.out.print('-'); writePositive(positiveAmount); } } //Precondition: amount >= 0; //Displays amount in dollars and cents notation. Rounds //after two decimal places. Omits the dollar sign. private static void writePositive(double amount) { int allCents = (int)(Math.round(amount * 100)); int dollars = allCents / 100; int cents = allCents % 100; System.out.print(dollars); System.out.print('.'); if (cents < 10) System.out.print('0'); System.out.print(cents); } /** Displays amount in dollars and cents notation. Rounds after two decimal points. Advances to the next line after output. */ public static void writeln(double amount) { write(amount); System.out.println( ); } } Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
