#1: Java can't format numbers
- Converting a binary number to a string is a very different operation than
writing bytes on a stream. Why should they be part of the same method?
java.text.NumberFormat
- Java can format numbers better than C, C++, Pascal, etc.
- Can group numbers by thousands with commas
- Can use non-European number systems
- Can adjust characters used for formatting
(e.g. parenthese for negative numbers)
- Exponential/scientific notation is an issue
import java.text.*;
public class PrettierTable {
public static void main(String[] args) {
NumberFormat myFormat = NumberFormat.getNumberInstance();
FieldPosition fp = new FieldPosition(NumberFormat.INTEGER_FIELD);
myFormat.setMaximumIntegerDigits(3);
myFormat.setMaximumFractionDigits(2);
myFormat.setMinimumFractionDigits(2);
System.out.println("Degrees Radians Grads");
for (double degrees = 0.0; degrees < 360.0; degrees++) {
String radianString = myFormat.format(Math.PI * degrees / 180.0,
new StringBuffer(), fp).toString();
radianString = getSpaces(3 - fp.getEndIndex()) + radianString;
String gradString = myFormat.format(400 * degrees / 360,
new StringBuffer(), fp).toString();
gradString = getSpaces(3 - fp.getEndIndex()) + gradString;
String degreeString = myFormat.format(degrees,
new StringBuffer(), fp).toString();
degreeString = getSpaces(3 - fp.getEndIndex()) + degreeString;
System.out.println(degreeString + " " + radianString
+ " " + gradString);
}
}
public static String getSpaces(int n) {
StringBuffer sb = new StringBuffer(n);
for (int i = 0; i < n; i++) sb.append(' ');
return sb.toString();
}
}
java PrettyTable | more
Degrees Radians Grads
000.00 000.00 000.00
001.00 000.01 001.11
002.00 000.03 002.22
003.00 000.05 003.33
004.00 000.06 004.44
005.00 000.08 005.55
006.00 000.10 006.66
007.00 000.12 007.77
008.00 000.13 008.88
009.00 000.15 010.00
010.00 000.17 011.11
011.00 000.19 012.22
012.00 000.20 013.33
013.00 000.22 014.44
014.00 000.24 015.55
015.00 000.26 016.66
016.00 000.27 017.77
017.00 000.29 018.88
018.00 000.31 020.00
019.00 000.33 021.11
020.00 000.34 022.22
Previous | Next | Top
Other Presentations
| Cafe au Lait Home
Last Modified May 16, 1999
Copyright 1999 Elliotte Rusty Harold
elharo@metalab.unc.edu