In this section, you will learn how to format a number using a custom format.
In this section, you will learn how to format a number using a custom format.In this section, you will learn how to format a number using a custom format.
A number can be formatted in different ways. Java has designed several classes to format the number. Using these classes, you can format the number into exponential notation, percentages, currency amounts etc. Here we are going to format a number using a custom message.
In the given example, we have used different pattern of special characters to specify the format of number. The method format() of NumberFormat class format the number in a specified pattern.
Here is the code:
import java.text.*; public class FormattingUsingCustomFormat { public static void main(String[] args) { NumberFormat nf1 = new DecimalFormat("000000"); String st1 = nf1.format(-1234.567); System.out.println(st1); NumberFormat nf2 = new DecimalFormat("##"); String st2 = nf2.format(-1234.567); System.out.println(st2); NumberFormat nf3 = new DecimalFormat("##00"); String st3 = nf3.format(0); System.out.println(st3); NumberFormat nf4 = new DecimalFormat(".00"); String st4 = nf4.format(-.567); System.out.println(st4); NumberFormat nf5 = new DecimalFormat("0.00"); String st5 = nf5.format(-.567); System.out.println(st5); NumberFormat nf6 = new DecimalFormat("#.#"); String st6 = nf6.format(-1234.567); System.out.println(st6); NumberFormat nf7 = new DecimalFormat("#.####"); String st7 = nf7.format(-1234.567); System.out.println(st7); NumberFormat nf8 = new DecimalFormat(".##"); String st8 = nf8.format(-1234.567); System.out.println(st8); NumberFormat nf9 = new DecimalFormat("#.000000"); String st9 = nf9.format(-1234.567); System.out.println(st9); NumberFormat nf10 = new DecimalFormat("#,###,###"); String st10 = nf10.format(-1234.567); System.out.println(st10); NumberFormat nf11 = new DecimalFormat("#;(#)"); String st11 = nf11.format(-1234.567); System.out.println(st11); NumberFormat nf12 = new DecimalFormat("'#'#"); String st12 = nf12.format(-1234.567); System.out.println(st12); NumberFormat nf13 = new DecimalFormat("'abc'#"); String st13 = nf13.format(-1234.567); System.out.println(st13); } }
Output:
-001235 |