Results 1 to 5 of 5
  1. #1
    pie_man is offline Member
    Join Date
    Jul 2011
    Posts
    2
    Rep Power
    0

    Default tiny offset in calculation

    Sometimes when i try to add, subtract, multiply, divide, etc. two doubles, i get this tiny offset of 0.000000000000001. For example, when i try to multiply 2.6 by 3.0, instead of getting 7.8, i get 7.800000000000001. Could someone please tell me how to fix this?

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    You can use formatting to specify how many decimal places. That's the only fix I can think of. Using floating point numbers in computers is simply not exact. There are a lot of resources on this topic around the internet if you are willing to read to understand it. Otherwise, you can just understand that using floating point will not produce exact results, and you should be careful if calculations require exact results.

    To format with String.format or System.out.printf(), use the %f flag, look up how to use them, and specify how many decimal places to show.

  3. #3
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,519
    Blog Entries
    7
    Rep Power
    20

    Default

    cenosillicaphobia: the fear for an empty beer glass

  4. #4
    pie_man is offline Member
    Join Date
    Jul 2011
    Posts
    2
    Rep Power
    0

    Default Thanks

    Thanks for the help :)

  5. #5
    neilcoffey is offline Senior Member
    Join Date
    Nov 2008
    Posts
    286
    Rep Power
    6

    Default

    There are a couple of approaches to this:

    (1) not care about the inaccuracy in the last decimal place and treat it as a display problem. As mentioned, you can do something like System.out.println("%.2f", number); to display to (in this case) 2 decimal places; (See the NumberFormat class if you need more control)
    (2) if you actually care about the inaccuracy for some reason, then see the BigDecimal class.

Similar Threads

  1. wunderground.com API GMT offset
    By SteveG in forum New To Java
    Replies: 2
    Last Post: 07-13-2011, 08:03 PM
  2. Tiny problem with Inheritance
    By MaceMan in forum New To Java
    Replies: 16
    Last Post: 04-19-2011, 02:14 PM
  3. Tiny Problem with JFrame
    By mr_anderson in forum AWT / Swing
    Replies: 3
    Last Post: 05-27-2010, 08:50 PM
  4. 'Tiny' 3D Problem
    By Supamagier in forum Advanced Java
    Replies: 2
    Last Post: 09-03-2009, 09:34 AM
  5. Tiny Eclipse 3.3
    By JavaBean in forum Java Software
    Replies: 0
    Last Post: 07-09-2007, 04:34 PM

Tags for this Thread

Posting Permissions

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