1 ÏÏÏimport java.text.*;
2 ÏÏÏimport
java.util.Locale;
3 ÏÏÏimport
java.util.Scanner;
4
5 ÏÕÖ×public class
PlayWithNumberFormatK
6 Ïϧ{
7 ÏϧÏÞßàpublic static void main (String []
args)
8 ÏϧÏϧ{
9 ÏϧÏϨ¹íÏNumberFormat
myNumberFormat; // object
declaration
10 ÏϧÏϨ¹íÏdouble value;
11 ÏϧÏϨ¹íÏString
outputForm;
12 ÏϧÏϨ¹íÏScanner
myScanner;
13 ÏϧÏϧ
14 ÏϧÏϧ
15 ÏϧÏϨ¹¹ÏmyScanner = new
Scanner(System.in);
16 ÏϧÏϨ¹¹Ïvalue =
myScanner.nextDouble();
17 ÏϧÏϧ
18 ÏϧÏϨ¹¹ÏSystem.out.println ("
unformatted value: " + value);
19 ÏϧÏϧ
20 ÏϧÏϨ¹¹ÏmyNumberFormat =
NumberFormat.getInstance(); // get one
21 ÏϧÏϧ
22 ÏϧÏϧ // things you can set with a number
formatter
23 ÏϧÏϨ¹¹ÏmyNumberFormat.setMinimumIntegerDigits(10);
24 ÏϧÏϨ¹¹ÏmyNumberFormat.setMaximumIntegerDigits(6);
25 ÏϧÏϨ¹¹ÏmyNumberFormat.setGroupingUsed(true); // commas or not
26 ÏϧÏϧ
27 ÏϧÏϧ // apply settings & print
28 ÏϧÏϧ // System.out.println
(myNumberFormat.format (value));
29 ÏϧÏϧ
30 ÏϧÏϧ // what you are
printing is a String so this is better
31 ÏϧÏϨ¹¹ÏoutputForm =
myNumberFormat.format (value);
32 ÏϧÏϨ¹¹ÏSystem.out.println
( "
formatted value 1: " + outputForm);
33 ÏϧÏϧ
34 ÏϧÏϧ // make some changes in the format
35 ÏϧÏϨ¹¹ÏmyNumberFormat.setMaximumFractionDigits(5);
36 ÏϧÏϨ¹¹ÏmyNumberFormat.setMaximumIntegerDigits(3);
37 ÏϧÏϨ¹¹ÏmyNumberFormat.setGroupingUsed(false);
38 ÏϧÏϧ
39 ÏϧÏϨ¹¹ÏoutputForm = myNumberFormat.format (value);
40 ÏϧÏϨ¹¹ÏSystem.out.println
( "
formatted value 2: " + outputForm);
41 ÏϧÏϧ
42 ÏϧÏϧ // change format to money
43 ÏϧÏϨ¹¹ÏmyNumberFormat =
NumberFormat.getCurrencyInstance();
44 ÏϧÏϨ¹¹ÏoutputForm =
myNumberFormat.format (value);
45 ÏϧÏϨ¹¹ÏSystem.out.println
( "
formatted value 3: " + outputForm);
46 ÏϧÏϧ
47 ÏϧÏϧ // change money format to English
48 ÏϧÏϨ¹¹ÏmyNumberFormat =
NumberFormat.getCurrencyInstance(Locale.UK);
49 ÏϧÏϨ¹¹ÏoutputForm =
myNumberFormat.format (value);
50 ÏϧÏϨ¹¹ÏSystem.out.println
( "
formatted value 4: " + outputForm);
51 ÏϧÏϧ
52 ÏϧÏϧ
53 ÏϧÏϧ // change
format to a percent
54 ÏϧÏϨ¹¹ÏmyNumberFormat =
NumberFormat.getPercentInstance();
55 ÏϧÏϨ¹¹ÏoutputForm =
myNumberFormat.format (value);
56 ÏϧÏϨ¹¹ÏSystem.out.println
( "
formatted value 5: " + outputForm);
57 ÏϧÏÏ©}
58 ÏÏ©}