Example of DecimalFormat
package com.dev2qa.example.java;
import java.text.DecimalFormat;
public class DecimalFormatExample {
public static void main(String args[])
{
// PI
double pi=3.1415927;
// Take one integer.
DecimalFormat df = new DecimalFormat("0");
System.out.println(df.format(pi)); // 3
//Take one integer and two decimal
df = new DecimalFormat("0.00");
System.out.println(df.format(pi)); // 3.14
// Take two integers and three decimals, and the inadequacies for integer are filled with 0.
df = new DecimalFormat("00.000");
System.out.println(df.format(pi));// 03.142
// Take all the integers.
df = new DecimalFormat("#");
System.out.println(df.format(pi)); // 3
// Count as a percentage and take two decimal places.
df = new DecimalFormat("#.##%");
System.out.println(df.format(pi)); //314.16%
// light speed.
long lightSpeed = 299792458;
// Display use scientific counting method and take five decimal places.
df = new DecimalFormat("#.#####E0");
System.out.println(df.format(lightSpeed)); //2.99792E8
// Use scientific counting method to show two integers and four decimal places.
df = new DecimalFormat("00.####E0");
System.out.println(df.format(lightSpeed)); //29.9792E7
//Each three integer are separated by commas.
df = new DecimalFormat(",###");
System.out.println(df.format(lightSpeed)); //299,792,458
//Embed formatting in text.
df = new DecimalFormat("The speed of light is ,### meters per second.");
System.out.println(df.format(lightSpeed));
}