1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Number formatting with DecimalFormat

Discussion in 'Java' started by pradeep, Dec 30, 2006.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    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:
    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:
    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:
    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.
     
  2. kiddo

    kiddo New Member

    Joined:
    Apr 11, 2009
    Messages:
    65
    Likes Received:
    1
    Trophy Points:
    0
    Nice...

    I've a question.... maybe some :p
    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.
     

Share This Page