The Artima Developer Community
Sponsored Link

Java Answers Forum
Dividing 2 double values

3 replies on 1 page. Most recent reply: Nov 1, 2003 6:05 PM by Senthoorkumaran Punniamoorthy

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 3 replies on 1 page
patoots

Posts: 6
Nickname: patoots
Registered: Oct, 2003

Dividing 2 double values Posted: Oct 30, 2003 10:42 PM
Reply to this message Reply
Advertisement
Hi! I'd like to know the reason behind the behavior of double when dividing 1 value over the other (both of double datatype)

double number1 = 100000.00;
double number2 = 50505.05;

double result = number2 / number1;

based on the above calculation, i ought to expect a result of 0.5050505 but the answer appeared to be 0.5050505000000001. How did this come to be?!?!?


Madhav Bhargava

Posts: 2
Nickname: utopians
Registered: Oct, 2003

Re: Dividing 2 double values Posted: Oct 31, 2003 1:54 PM
Reply to this message Reply
Non repeating decimals in base 10 can be repeating in base 2. This might be the reason why u do not get what u expect..

Jonathon Brozny

Posts: 24
Nickname: jonathon
Registered: Oct, 2003

Re: Dividing 2 double values Posted: Nov 1, 2003 10:10 AM
Reply to this message Reply
doubles are not accurate. Even subtracting with them sometimes will give similar results. If you want something that will give you the expected answer all the time check out something like BigDecimal.

http://java.sun.com/j2se/1.4.2/docs/api/java/math/BigDecimal.html

Senthoorkumaran Punniamoorthy

Posts: 335
Nickname: senthoor
Registered: Mar, 2002

Re: Dividing 2 double values Posted: Nov 1, 2003 6:05 PM
Reply to this message Reply
BigDecimal is right way to go I guess but if you think BigDecimal is too heavy for your work you can use integers. You got to convert both numbers to integers before calculation and then convert them back to double.

Flat View: This topic has 3 replies on 1 page
Topic: tomcat and hssf Previous Topic   Next Topic Topic: Cannot get program to properly count tokens

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use