Results 1 to 6 of 6
  1. #1
    africanhacker is offline Senior Member
    Join Date
    Feb 2011
    Posts
    107
    Rep Power
    0

    Default keep double accurate to two decimal places

    Hie guys I have a double variable that holds product costs after multiplying cost per kg with the actual weight selected. How do I keep the numbers accurate to just two decimal places. I don't want numbers like $2.555555578, instead I need $2.55. Please help.

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

    Default

    Use BigDecimal. Or if it's just the display of the numbers that's bothering you, DecimalFormat.

    db

  3. #3
    africanhacker is offline Senior Member
    Join Date
    Feb 2011
    Posts
    107
    Rep Power
    0

    Default

    Thanks for that, Decimal Format did it. Some rep for you :D

  4. #4
    Iron Lion is offline Senior Member
    Join Date
    Nov 2010
    Posts
    210
    Rep Power
    5

    Default

    Alternatively, you might want to consider using an int and keeping track of the amount in cents instead of dollars.

  5. #5
    africanhacker is offline Senior Member
    Join Date
    Feb 2011
    Posts
    107
    Rep Power
    0

    Default

    @Iron Lion

    That is really clever. I had actually never thought of that.

    In real world application how is it done?

  6. #6
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

    Default

    In real world applications, floating point is (almost) never used for currency calculations. Integral types are used for the lowest currency unit and the decimal point is inserted for display/printout purposes only.

    db

Similar Threads

  1. 3 Decimal Places
    By benhawk in forum New To Java
    Replies: 7
    Last Post: 11-02-2010, 10:28 PM
  2. Limiting decimal places in a double
    By darek9576 in forum New To Java
    Replies: 5
    Last Post: 03-14-2010, 02:13 AM
  3. rounding double to two decimal places
    By javaMike in forum Advanced Java
    Replies: 15
    Last Post: 03-10-2010, 01:04 AM
  4. Replies: 4
    Last Post: 03-03-2009, 01:43 PM
  5. numbers with two decimal places
    By little_polarbear in forum New To Java
    Replies: 8
    Last Post: 08-28-2008, 12:04 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •