Wednesday, June 27, 2012

Still Counts in Base 2

So one week done with the Java CS 55 course. We've reviewed some things that I never understood which are doubles. Double in Java is a decimal number. But when you add two doubles, you usually get a formatted number like such: 2.00 + 3.00 = 5.0000004

I wasn't sure why but I did some digging. Double is where the computer assigns the decimals as though in base 2, so 2^-6th would be something like a fractional decimal to count in which gives us the 0.00004 at the end of a double arithmetic. So it was odd when I'd arrive with a simple program adding two double numbers and get a sum. Thankfully in Java there's a class called DecimalFormat in the java.text.* package which allows me to force a specific format of the decimals as a method.

Like so:

public static void main(String[] args)
DecimalFormat f= new DecimalFormat("0.000");
String numStr1 = JOptionPane.showInputDialog("Enter an Integer");
double n1 = Double.parseDouble(numStr1);
String numStr2 = JOptionPane.showInputDialog("Enter an Integer");
double n2 = Double.parseDouble(numStr2);
double total = n1+n2;
System.out.println("Total is "+total);
System.out.printf("Total is %6.2f\n", (n1+n2));
System.out.println("Total is "+f.format((n1+n2)));

This will give you three outputs, one is the unformatted normalized total, second is a float like total printed (something in C you can do all the time), and finally the formatted output.

I guess that also includes the code of the post. Till next time :)

No comments: