Loosing precision when computing

Hi everyone ! I've got a problem with math operation. I loose precision on simple operations, and i can't understand why.
I've got a JTable with several rows. Each row represent a product, that I need to order. After filling this table with some products, some prices, and the number of products to order, the method "computeTotal()" is going to compute the total price of the order. The method will scan the table and read each price, and number of articles to order, and add it to the total price.
The problem : on some basic operations, I'm loosing precision. For example : 4.34 * 45 = 195.3 but my method compute 195.29999999999998 and I don't know why.
here's is the sample of code :
      * Get the total price of an order
      * @return the price of the order
     private double computeTotal(){
          int rowCount = this.tableModel.getRowCount();
          double totalotal = 0;
          for(int i = 0;i < rowCount;i++){
                * To compute the total of a line, I need the number of products ordered, and the price of the product
               int nbArt = ((Integer)tableModel.getValueAt(i,13)).intValue();
               double price = ((BigDecimal)tableModel.getValueAt(i,4)).doubleValue();
               double totalProducut = nbArt * price;
               total += totalProduct;
          return total;
     }what can I do ? what are the possibilities to adjust the precision ?
Thanks a lot for your help.
J�r�me Bogaerts,
Belgium

Hi,
This is a common asked question, and you would have
been able to find the answer if you only googled for
a minute or two.
What Every Computer Scientist Should Know About
Floating-Point Arithmetic
http://docs.sun.com/source/806-3568/ncg_goldberg.html
Use BigDecimal
/KajThanks a lot for your response. Know i've got something to read this night !
Greetings,
J�r�me Bogaerts

Similar Messages

  • How not to loose precision when exporting to dxf?

    When a simple line drawing of exactly 1780.00mm wide is exported into a new dxf file and that file is imported back into illustrator CS4 the precision of the imported drawing is not the same. Often about 0.2 mm smaller.Tried other units, did't  work. Snap to grid/point was switched off. I need the exact size again..
    I hope somebody can help?! Many thanks.

    Niffo,
    Of course I understand the importance of accuracy, especially if the design will be transfered to physical fabrication. But what I'm suggeting is that you aren't losing "image size," but rather losing "line weight" or at least its reference. As a result, you may be seeing a different dimension. Consider this oversimplifcation:
    Dimension A = the distance between the lines.
    Dimension B = the distance between the line weights at their outer extents.
    Could it be that the dimensions of your drawing are being measured at different points pre-dxf export and post-dxf import?
    I don't know, but this is the possibility I was presenting in my previous post.

  • I am using the latest iTunes on my laptop without iCloud.  I would like to use a different computer on my network at home but I'm afraid I will loose evrything when I install iTunes

    I am using the latest iTunes on my laptop without iCloud.  I would like to use a different computer on my network at home but I'm afraid I will loose evrything when I install iTunes

    Drrhythm2 wrote:
    What's the best solution for this? I
    Copy the entire /Music/iTunes/ folder from her old compouter to /Music/ in her account on this new computer.

  • Using Outlook 2007 I want to receive emails on my iPhone 4 only when Outlook is NOT open on my computer, as when away from home or want to quickly check email when computer is not turned on. Either ALL emails come to my iPhone or none at all.

    Using Outlook 2007 I want to receive emails on my iPhone 4 only when Outlook is NOT open on my computer, as when away from home or want to quickly check email when computer is not turned on. Either ALL emails come to my iPhone or none at all. Is the setting I need to change in Outlook or on the iPhone or is it somewhere else?  I used to have this setting but transferring Outlook to a new laptop somehow turned it off.

    No. You really can't do that. Not easily at any rate. You would have to set them both up to use POP3, but even then there is no way to guarantee that the phone won't poll the server prior to your computer doing so, pulling down the message from the server.

  • Two computers share the same wi-fi Modem . When computer A reads a message it is marked as read on both PC's, not allowing computer B to see what must be read.

    Two computers share the same WI-fi Modem . When computer A reads a message it is marked as read on both PC's, not allowing computer B to see what must still be read. Email is Thunderbird.
    Please help, Thank you for this online support option

    Imap wasn't designed for this kind of multi user situation. It assumes that you the account owner will be using it to manage one account via multiple devices. So once you have read a message it has been read, regardless of which device you were using at the time.
    You appear to be describing a situation where you want more than one user to read each message, without anyone knowing if anyone else has read it or even dealt with it. Frankly, I can't imagine a set of circumstances where this workflow would make sense or be useful.
    You can do various things such as manually setting messages as unread, or moving them from one folder to another to indicate that they have been processed, but much of this relies on users being thorough and conscientious.
    You may need to be running your own server to do this sort of email message managing, if you really need to fork a message so it gets to multiple recipients. Managing which users see a particular message is a job for a server, not the end-user's email client.

  • Hi. I wanna know the reason whyI can't sync my ipad to my computer. It says that sync will resume when (computer's name) is available? My device runs with ios6.1.3 and itunes 11. Please answer. Thanks.

    Hi. I wanna know the reason whyI can't sync my ipad to my computer. It says that sync will resume when (computer's name) is available? My device runs with ios6.1.3 and itunes 11. Even I would like to transfer and view photos using the USB cable, it doesn't appear in the computer. Please answer. Thanks.

    Hi Lauren ...
    Try the troubleshooting steps here > iOS: Device not recognized in iTunes for Windows

  • Get error message that skype has problem loading when computer is turned on the first time every day. this started when the latest firefox v6.0 was downloaded.

    get error message that skype has problem loading when computer is turned on the first time every day. this started when the latest firefox v6.0 was downloaded.

    ''mbratlie [[#question-1055011|said]]''
    <blockquote>
    It was working fine and I had no problems, and then one day I tried opening a window and it froze. When I tried quiting the program my whole window went black. The x to the close the window doesn't work. The only option I have in my tool bar is Firefox and nothing happens when I try to quit firefox. Every time I try to shut down my computer Firefox prevents it. I haven't updated Firefox yet, so it's an older program, but only by a month or two. What's going on and how do I fix it?
    </blockquote>
    This is the first time it's ever happened. I downloaded the new operating system for Firefox but I can't install it until the Firefox currently running on my laptop quits, which it won't.

  • (early 2014) rMBP abruptly goes black (sleep mode) when computer is tilted at certain angles or lifted.

    My (early 2014) rMBP abruptly goes black (sleep mode) when computer is tilted at certain angles or lifted. Ive reset Energy saver mode to factory defaults and the problem still occurs.

    Please make a Genius Appointment and take it in for service.

  • Why do my programs close when computer goes to sleep

    why do my programs close when computer goes to sleep?

    What do you mean by "close"? Your open applications stay open when you put your computer to sleep. However, if you have an app like iMovie open, for example, and you are exporting a video, than exporting will pause when your computer is asleep.

  • Battery on iBook G4 running down when computer shutdown??

    The battery on my 2004 iBook G4 runs down even when computer is shut down. I have looked at the
    energy preference but can't figure out what is triggering the computer back on to do this. There is
    nothing in preferences set to turn the computer on.

    audrey e.fromsun city west wrote:
    The battery on my 2004 iBook G4 runs down even when computer is shut down. I have looked at the
    energy preference but can't figure out what is triggering the computer back on to do this. There is
    nothing in preferences set to turn the computer on.
    First you say that the battery runs down while the computer is shut down.
    Then you say that the computer comes back on.
    Which is it? Does the computer start up all by itself?
    Have you tried resetting the PMU? The PMU (Power Management Unit) has control over both the sleep and charging functions, so resetting it may help.

  • Thunderbolt ethernet not working when computer wake up from sleep.

    thunderbolt ethernet not working when computer wake up from sleep.
    it will not happen in Mountain loin.

    I had this problem on SL and on Lion as well, and it occures for WiFi and Ethernet connections.
    In fact the internet connection was not broken as I could ping the destination usin the IP (not DNS name).
    In this case the problem was related to mDNSResponder task which handles all dns queries.
    It was the most frequent problem in my day to day work with SL and now Lion. It was never fixed by any patch from Apple. I tried almost all voodoo including fresh install, all possible config changes - no solution.
    The only version with no problems related to network was 10.5.8. All the other versions had issues of different kind (WiFi instability (lost signal), DNS problems (for wireless and wired connection) sometimes associated with machine sleep and wake up and sometimes with no reason.
    QUESTION: Is your problem independent of the access point / router you connect to.
    I must say networking was (and still is) the weakest part, besides the other OS X weaknesses I experienced during 4 years of OS X usage.
    No problems in the same network with Linux or Windows beeing ran natively on my iMac So hardware is OK.
    Software is of poor quality. Not much more to say in this matter.
    I found a very interesting article dated 1996 about programming which I think is still valid.
    Link to the article: http://www.fastcompany.com/magazine/06/writestuff.html
    Below the fragment (with some connection to Apple)
    Software is everything. It also s***s.
    "It's like pre-Sumerian civilization," says Brad Cox, who wrote the software for Steve Jobs NeXT computer and is a professor at George Mason University. "The way we build software is in the hunter-gatherer stage."

  • Since I upgraded to Maverick when computer sleeps it will not wake up but must be restarted?  Also password to icloud is never saved?

    Since I upgraded to Maverick when computer sleeps it will not wake up but must be restarted?  Also password to icloud is never saved?

    I read someone said you can tap on "other" when selecting which wifi you connect to and then entering the exact wifi name of the network you wish to join and the password and then joining that network allowed the password to be saved.  Also with iOS 6 the minimum length of the password needs to be 8 characters.  Maybe you password on your router is less than 8 characters long

  • TS2972 Apple tv sleeps when computer sleeps. What to do

    The TV disconnects from Apple TV sharing when computer sleeps. What to do?

    George, Your trouble sounds just like mine. You can read my thread here: https://discussions.apple.com/thread/4204561?start=0&tstart=0, but in summary:
    Itunes and the Apple TV exchange messages about once per minute. If any wifi interference stops the message-and-reply, iTunes closes the home sharing connection.  Other services are usually fine.
    I solved my problems by wiring the ATV and computer. (Wiring either alone didn't work.)  Home Sharing is now rock solid and works exactly as advertised. No drop-outs during play. The iTunes library is always available on ATV - I never have to restart home sharing or iTunes or the ATV. If a computer or ATV restarts, they pair up automatically.
    Not everyone can wire, I know. But it worked for me. Test it if you can.
    John

  • PPPoE Still Disconnects When Computer Sleeps

    With 10.9.2 and again with 10.9.3, PPPoE disconnects when computer sleeps.  This didn't happen with OS 8.x, OS 9.x, OS X 10.2, 10.8.x, 10.9.0, or 10.9.1.  System Preferences>Energy Saver is set for display and computer to sleep after about 12 minutes.  I'd rather not set computer to never sleep.  Please advise and correct for 10.9.4.  Thank you.

    I have the same issue. Also after wake-up connecting to PPPoE is a challenge, because it establishes only after 5-7 attemps (Authentication failed). I guess 10.9.3 update causes this.

  • P2055 randomly runs a Print Page before a job, and randomly when computer is on

    Before many print jobs, the P2055dn prints a page that is blank except for the follwing at the top of the page:  GET /DevMgmt/DiscoveryTree.xml  HTTP/1.1
    Host: 127.0.0.1:8080
    How can I make this stop?  I have the latest print drivers.  Running Win 7 64 bit.

    2605dn has same problem as P2055 randomly runs a Print Page before a job, and randomly when computer is on
    Before many print jobs, the 2605dn prints a page that is blank except for the follwing at the top of the page: GET /DevMgmt/DiscoveryTree.xml HTTP/1.1
    Host: 127.0.0.1:8080
    How can I make this stop? I have the latest print drivers. Running Win 7 64 bit.
    The fix for the 2055dn does not work on the 2605dn so does anyone have a fix for 2605dn - tech help and driver useless as usual

Maybe you are looking for

  • Itunes closes with an error message after installation

    Right basically had the whole updater ruining my ipod problem, finally got a replacement today. Problem is when i spoke to apple tech support, for an 1 hour and 20 minutes the guy was getting me to mess about with my installation of itunes and system

  • IPhone 4 Bumper damages antenna steel band

    Hello, I'm opening this topic because the Apple support system doesn't really offer me any decent method to ask Apple what to do. I've got two issues: First, the Bumper I ordered during the case program is falling apart. The rubber comes off the plas

  • Crystal Reports and SQLite

    Hello, I work with Crystal Reports 2008. We have a report connected to a Sybase database via ODBC. I tried to replace the Sybase database by a SQLite database 3.6.11 via ODBC. But it doesn't act up, even though the databases contain the same tables.

  • Getting the Intended Target for a Request

    I now know how to set the target for a response: HttpServletResponse.setHeader("Window-target","myFrameName") My next question is how do I determine the intended target of the initial request, before I set it to something else with the above code? It

  • Boolean conversion

    How can I convert a Boolean expression into a string? I know the toString method is used. Can someone show some sample code that it is used in? I am attempting to finish a program and am trying to use the toString method. Thanks In Advance, Patrick d