Home Java Beginners Decimal Format Example
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Decimal Format Example

Advertisement
Here, we are discussing how to format a decimal value by giving an example.

Decimal Format Example

     

In this example we are going to format a decimal value.

In this example we are talking a double value. We are creating an object of DecimalFormat(String format_type) class .In DecimalFormat class we are passing "0.000" .This is used to create an decimal format which display three digits after decimal point. We are using NumberFormat to store the reference of  object of DecimalFormat with name of formatter. To apply the format on double value we are using  format() method.

The code of the program is given below:

import java.text.DecimalFormat;
import java.text.NumberFormat;
 
public class DecimalFormatExample
{
  public static void main(String args[])
  {
  double amount = 2192.015;
  NumberFormat formatter = new DecimalFormat("#0.000");
  System.out.println("The Decimal Value is:"+formatter.format(amount));
  }
} 

The output of the program is given below:

C:\convert\rajesh\completed>javac DecimalFormatExample.java
C:\convert\rajesh\completed>java DecimalFormatExample
The Decimal Value is:2192.015

Download this example.

Advertisement

Liked it!  Share this Tutorial


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: June 29, 2007

Ask Questions?    Discuss: Decimal Format Example   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Eli
June 7, 2011
Awesome

Thanks for the post - it worked perfectly!
Alex
March 15, 2013
code example is not good

You should put more thought in your example. Try to use some value of double amount that doesn't match your formatter already; that is, has more/less digits after decimal point than in your pattern. Otherwise, System.out.println("The Decimal Value is:" + amount); will give you exactly the same output as your System.out.println("The Decimal Value is:"+formatter.format(amount)); Your example says nothing about rounding numbers.
DMCA.com