Solved

Double number Rounding issue

Posted on 2004-03-24
6
172 Views
Last Modified: 2010-04-01
Hi Experts,

Look at the simple example

double a = 1440.0;
double b = 0.06;
double c = a * b;

out.println("Result " + c)  gives 86.39999999999999;

Where
out.println("Result " + 1440.0 * 0.06) gives exact value 86.4   which is correct;

Does anybody knows why this happens, and how to fix a*b -> 86.4


Thanks
Britto
0
Comment
Question by:de_britto
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
6 Comments
 
LVL 27

Accepted Solution

by:
rrz earned 25 total points
ID: 10672181
>out.println("Result " + 1440.0 * 0.06) gives exact value 86.4   which is correct;
I don't get that result on my Tomcat 5 and  JDK1.4 .  I get   86.39999999999999  

>how to fix a*b -> 86.4
Here is one way.  

<%
float a = 1440.0f;
float b = 0.06f;
float c = a * b;
out.println("Float Result = " + c);  
%>
0
 
LVL 92

Assisted Solution

by:objects
objects earned 25 total points
ID: 10674232
Use DecimalFormat class to display to the number of required decuimal places.


DecimalFormat df = new DecimalFormat("#.##");
out.println("Result "+df.format(c));  
0
 
LVL 9

Expert Comment

by:mmuruganandam
ID: 10674601
DecimalFormat format = new DecimalFormat("#.#");
out.println(format.format(c));            
0
 
LVL 27

Expert Comment

by:rrz
ID: 10678566
to objects and mmuruganandam,  
Great, your solutions work for the given values, because DecimalFormat uses half-even rounding  for formatting.  

 "de britto" wanted the  exact value
>gives exact value 86.4   which is correct  

But what if the variables change ?  (  b = 0.061111 for example )  
How could your solution be applied to the general case ?  

0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Enabling the Skype for Business Meeting Scheduler in Hybrid OWA
Azure Functions is a solution for easily running small pieces of code, or "functions," in the cloud. This article shows how to create one of these functions to write directly to Azure Table Storage.
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

735 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question