Metode Pengaturan Format
- Menggunakan Method System.out.format()
- Menggunakan DecimalFormat Class
1. Method System.out.format()
public class TestFormat {
public static void main(String[] args) {
long n = 461012;
System.out.format(“%d%n”, n);
System.out.format(“%08d%n”, n);
System.out.format(“%+8d%n”, n);
System.out.format(“%,8d%n”, n);
System.out.format(“%+,8d%n%n”, n);
double pi = Math.PI;
System.out.format(“%f%n”, pi);
System.out.format(“%.3f%n”, pi);
System.out.format(“%10.3f%n”, pi);
System.out.format(“%-10.3f%n”, pi);
Calendar c = Calendar.getInstance();
System.out.format(“%tB %te, %tY%n”, c, c, c);
System.out.format(“%tl:%tM %tp%n”, c, c, c);
System.out.format(“%tD%n”, c);
}
}
Hasil Eksekusi
461012
00461012
+461012
461,012
+461,012
3.141593
3.142
3.142
3.142
May 29, 2006
2:34 am
05/29/06
2. DecimalFormat Class
public class DecimalFormatDemo {
public static void main(String[] args){
DecimalFormat formatku = new DecimalFormat(“###.##”);
//String output = formatku.format(45.8398767);
//System.out.println(output);
System.out.println(formatku.format(45.8398767));
}
}
DecimalFormatDemoLengkap
public class DecimalFormatDemoLengkap{
static public void customFormat(String pattern, double value ) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + ” ” + pattern + ” ” + output);
}
static public void main(String[] args) {
customFormat(“###,###.###”, 123456.789);
customFormat(“###.##”, 123456.789);
customFormat(“000000.000”, 123.78);
customFormat(“$###,###.###”, 12345.67);
}
}
Hasil Eksekusi
123456.789 ###,###.### 123,456.789 123456.789 ###.## 123456.79 123.78 000000.000 000123.780 12345.67 $###,###.### $12,345.67
Tinggalkan komentar