1 / 8

TestFormat

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("###,###,###.##");

wynn
Download Presentation

TestFormat

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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])); • } • } • }

  2. output • 1,120 • 111,225.5 • 50,000.67

  3. double [] number = {1120, 111225.500, 50000.67, 1000000076.989}; • 1,120 • 111,225.5 • 50,000.67 • 1,000,000,076.99

  4. ###,###,###.## • 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 “,”

  5. 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])); • } • } • }

  6. output • 1?120 • 111?225,5 • 50?000,67 • 1?000?000?076,989 • Notice it didn’t round up like before

  7. 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)); • } • }

  8. output • 10 • 100 • 1,000 • 10,000

More Related