1. Introducing Channels - a new way to chat with other Android users!
    Dismiss Notice

Major Bug!! Java or android itself?


Last Updated:

  1. karimamin

    karimamin New Member This Topic's Starter

    Joined:
    Sep 3, 2010
    Messages:
    2
    Likes Received:
    0
    If you run the following expression
    102 * 0.0254
    you will get 2.59079999999998

    but the answer is 2.5908
    But yet, multiple 102 * 0.0253 or 102*0.0255 or 102*0.0256 and you get the right answer!! Just with this number. This fails on both the emulator for eclipse and on my actual htc phone.:mad:

    Help! Can anyone help me solve this problem?
     

    Advertisement
  2. meackerman

    meackerman Active Member

    Joined:
    Aug 22, 2010
    Messages:
    36
    Likes Received:
    5
    Welcome to the world of Java and double precision numbers. Same thing happens in Windows and everywhere else. Its not a "bug" but the way Java double precision numbers are implemented.
     
  3. karimamin

    karimamin New Member This Topic's Starter

    Joined:
    Sep 3, 2010
    Messages:
    2
    Likes Received:
    0
    I'm basically trying to make a simple calculator and found this number totally at random. The calculator on my phone calculates this properly so why can't my app? I guess i'm trying to get is what are the workarounds for this as I take it there must be for the calculator software to work properly.
     
  4. dCoder

    dCoder Member

    Joined:
    Jul 18, 2010
    Messages:
    13
    Likes Received:
    3
    Try using BigDecimal instead of Double.
     
  5. Doug Simmons

    Doug Simmons Member

    Joined:
    Mar 19, 2010
    Messages:
    15
    Likes Received:
    6
    I love this thread. Thanks. :)
     
  6. meackerman

    meackerman Active Member

    Joined:
    Aug 22, 2010
    Messages:
    36
    Likes Received:
    5
    even BigDecimal isn't perfect, but it works much better. We typically don't worry about the rounding error too much since we usually round to a particular level of precision when we display a number to the user, but that doesn't work so well with a calculator app.

    I've written write code that'll take a number like 2.59079999999998 and figure out its really 2.5908 for the cases where we don't know the level of precision beforehand.
     

Share This Page

Loading...