Financial.java


Below is the syntax highlighted version of Financial.java from §9.1 Scientific Computation.



/******************************************************************************
 *  Compilation:  javac Financial.java
 *  Execution:    java Financial
 * 
 *
 ******************************************************************************/

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Financial {

    public static void main(String[] args) { 

        // binary floating point arithmetic
        double a = 1.09 * 50;
        StdOut.println("1.09 * 50 = " + new BigDecimal(a));
        StdOut.println("rounds to   " + Math.round(a));

        double b = 1.14 * 75;
        StdOut.println("1.14 * 75 = " + new BigDecimal(b));
        StdOut.println("rounds to   " + Math.round(b));

        double c = 1.05 * 0.70;
        StdOut.println("1.05 * 0.70 = " + new BigDecimal(c));
        StdOut.println("rounds to   " + Math.round(c));

        // exact arithmetic
        BigDecimal a1 = new BigDecimal("1.09");
        BigDecimal a2 = new BigDecimal("50");
        BigDecimal a3 = a1.multiply(a2);
        StdOut.println(a3 + " " + a3.setScale(0, RoundingMode.HALF_EVEN));

        BigDecimal b1 = new BigDecimal("1.14");
        BigDecimal b2 = new BigDecimal("75");
        BigDecimal b3 = b1.multiply(b2);
        StdOut.println(b3 + " " + b3.setScale(0, RoundingMode.HALF_EVEN));

     }

}


Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne.
Last updated: Fri Oct 20 14:12:12 EDT 2017.