*
The moose likes Performance and the fly likes Casting from double to int leading to in correct data for very specific numbers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Performance
Bookmark "Casting from double to int leading to in correct data for very specific numbers" Watch "Casting from double to int leading to in correct data for very specific numbers" New topic
Author

Casting from double to int leading to in correct data for very specific numbers

H Und
Greenhorn

Joined: Mar 25, 2010
Posts: 7
We just came across the following thing, which is very interesting and misleading the other program by its outcome. Could you please tell me, what is wrong with the following little program.


public class CastingClass {

static double x = 269.28;
public static void printValue(){
System.out.println("Original Value: " + x);
System.out.println("Before Casting; " + x * 100);
int i = (int) (x * 100);
System.out.println("After Casting: " + i);
}
static public void main(String[] args){
printValue();
}
}



// I am getting the following result, which is not correct.

-------------------------------------------------
Original Value: 269.28
Before Casting, but multiplying with 100: 26927.999999999996
After Casting: 26927

---------------------------------------------------------
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18486
    
  40

H Und wrote:We just came across the following thing, which is very interesting and misleading the other program by its outcome. Could you please tell me, what is wrong with the following little program.


public class CastingClass {

static double x = 269.28;
public static void printValue(){
System.out.println("Original Value: " + x);
System.out.println("Before Casting; " + x * 100);
int i = (int) (x * 100);
System.out.println("After Casting: " + i);
}
static public void main(String[] args){
printValue();
}
}



// I am getting the following result, which is not correct.

-------------------------------------------------
Original Value: 269.28
Before Casting, but multiplying with 100: 26927.999999999996
After Casting: 26927

---------------------------------------------------------



Take a look at point #20 here... http://www.coderanch.com/how-to/java/JavaBeginnersFaq


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Casting from double to int leading to in correct data for very specific numbers
 
Similar Threads
importance of parameter
What is the output for the below code is different?
help me in kicking off the bug from the following code
'Implied Decimal' format in Java for Double/Float
Some Runtime vs. Compile Time SCJP 6.0 Mock Exam Questions