80 likes | 218 Views
TestFormat. import java.text.*; import java.util.*; public class TestFormat{ public static void main(String [] args){ Terminal output = new Terminal(); double [] number = {1120.0, 111225.500, 50000.67}; DecimalFormat deci = new DecimalFormat("###,###,###.##");
E N D
TestFormat • import java.text.*; • import java.util.*; • public class TestFormat{ • public static void main(String [] args){ • Terminal output = new Terminal(); • double [] number = {1120.0, 111225.500, 50000.67}; • DecimalFormat deci = new DecimalFormat("###,###,###.##"); • for(int x = 0; x < number.length; x++){ • output.println(deci.format(number[x])); • } • } • }
output • 1,120 • 111,225.5 • 50,000.67
double [] number = {1120, 111225.500, 50000.67, 1000000076.989}; • 1,120 • 111,225.5 • 50,000.67 • 1,000,000,076.99
###,###,###.## • The number can have at most 2 digits after the decimal point • The NumberFormat doesn’t just drop the extra digits but rounds up • #,###.## would have worked the same • ###.## would not have the “,”
For those in France • import java.text.*; • import java.util.*; • public class TestFormat{ • public static void main(String [] args){ • Terminal output = new Terminal(); • double [] number = {1120, 111225.500, 50000.67, 1000000076.989}; • DecimalFormat deci = new DecimalFormat("#,###.##"); • for(int x = 0; x < number.length; x++){ • deci = (DecimalFormat)deci.getInstance(Locale.FRANCE); • output.println(deci.format(number[x])); • } • } • }
output • 1?120 • 111?225,5 • 50?000,67 • 1?000?000?076,989 • Notice it didn’t round up like before
AlignIntegers from the web • public class AlignIntegers • { • static String align(NumberFormat fmt, int n, int sp) • { • StringBuffer buf = new StringBuffer(); • FieldPosition fpos = new FieldPosition(NumberFormat.INTEGER_FIELD); • fmt.format(n, buf, fpos); • for (int i = 0; i < sp - fpos.getEndIndex(); ++i) • buf.insert(0, ' '); • return buf.toString(); • } • public static void main(String[] args) • { • NumberFormat fmt = NumberFormat.getInstance(); • System.out.println(align(fmt, 10, 9)); • System.out.println(align(fmt, 100, 9)); • System.out.println(align(fmt, 1000, 9)); • System.out.println(align(fmt, 10000, 9)); • } • }
output • 10 • 100 • 1,000 • 10,000