Home Tutorial Java Corejava Javatext Formatting a Number Using a Custom Format

 
 

Share on Google+Share on Google+
Formatting a Number Using a Custom Format
Posted on: October 9, 2010 at 12:00 AM
Advertisement
In this section, you will learn how to format a number using a custom format.

Formatting 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
-1235
00
-.57
-0.57
-1234.6
-1234.567
-1234.57
-1234.567000
-1,235
(1235)
-#1235
-abc1235

Advertisement

Related Tags for Formatting a Number Using a Custom Format:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 9, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com