Formatting Output Slides by Dr. Heuring In the current version of Java you may format your output using a couple of classes. Classes are in java.text.* package. DateFormat DecimalFormat MessageFormat SimpleDateFormat
Formatting a Decimal DecimalFormat f = new DecimalFormat("###,###.00"); double value1 = 1224.567, value2=0.4, value3 = -10000.0; System.out.println("Value1 = "+f.format(value1)); System.out.println("Value2 = "+f.format(value2)); System.out.println("Value3 = "+f.format(value3)); Output: Value1 = 1,224.57 Value2 = .40 Value3 = -10,000.00
The DecimalFormat Symbols 0 – digit or 0 if no digit. # -- digit or blank if absent . – decimal separator - -- minus sign , -- Grouping Separator E – separator for mantissa and exponent in scientific notation ; -- separates positive and negative subpatterns % -- multiply by 100 and show as a percnetage
Another Example for Decimals DecimalFormat f2 = new DecimalFormat( " ###,##0.00;-###,##0.00"); System.out.println("Value1 = "+f2.format(value1)); System.out.println("Value2 = "+f2.format(value2)); System.out.println("Value3 = "+f2.format(value3)); Output Value1 = 1,224.57 Value2 = 0.40 Value3 = -10,000.00