Number formatting with DecimalFormat

pradeep's Avatar author of Number formatting with DecimalFormat
This is an article on Number formatting with DecimalFormat in Java.
The Decimal Format class is not very well documented, so I will try and exmplain it with an example.

Firstly, you need to import the DecimalFormat class:

Code: Java
import java.text.DecimalFormat;
 
Create an instance the format object. This object can be used with doubles, as it uses a decimal. It uses a template String to teach Java how to ouput the objects.

I am using this as a standard format of money:

Code: Java
DecimalFormat money = new DecimalFormat("$0.00");
Now that you have the money object. (declared either globally or locally) you can now format your objects

Note: This example uses only 2 decimal places and a $, but any symbols or length is available.

As an example of prniting a double value:

Code: Java
double amount = 4.333333333;
System.out.println(money.format(amount));
The output is: $4.33 as described by the template, this handles your percision and dollar sign with a single template.
Contributor
30Apr2009,13:37   #2
kiddo's Avatar
Nice...

I've a question.... maybe some
I got a project, maybe not a project,
just a small programme.

I want to make it looks like a table,
but everytime I run it,
the position of the coulumn and row weren't fit,
it wasn't look like a table.

Can you tell me how can I manipulate the output,
so it will look neat?

E.g :

Name Phone Address
--------------------------------------------
one 001101 one street
~~~ ~~~~~ ~~~~~~
~~~ ~~~~~ ~~~~~~
~~~ ~~~~~ ~~~~~~


-----------------------------------------------------------------------

Sorry if my English not so good.
I'll improve it.