Question about an output using the (int) statement

Folks,

I am new to java and ran a simple problem that takes a user input as a double, multiplies it by 100 and then applies (int) to that double and prints the output. See code below. I ran it with a handful of number and received the expected output except 19.99. It returns 1998.0, not the expected 1999.0.

I understand precision maybe rearing its ugly head here, I just wanted to know if anyone can shed any light on why it happens with 19.99?

PS im using eclipse with JRE 1.6.

Thank you!

import java.util.Scanner;

publicclass IntegerProblemClass{

publicstaticvoid main(String[] args){

System.out.println("Choose any number");

Scanner userInput =new Scanner(System.in);

double userNum = userInput.nextDouble();

userNum = (int)(userNum * 100);

System.out.println("Your new number is: " + userNum);

}

}

[1351 byte] By [jmmorina] at [2007-11-26 17:22:09]
# 1
The cast to int truncates the decimal portion.System.out.println(19.99 * 100); // 1998.9999999999998~
yawmarka at 2007-7-8 23:50:08 > top of Java-index,Java Essentials,New To Java...
# 2

If you wish to round, you can use [url=http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Math.html#round(double)]Math.round()[/url]:

public class Test {

public static void main(String[] args) {

double input = 19.99;

long rounded = Math.round(input * 100);

System.out.println(rounded);

}

}

DrLaszloJamfa at 2007-7-8 23:50:08 > top of Java-index,Java Essentials,New To Java...
# 3

And if it's just a matter of display, you can always use an appropriate formatter. Example:

double d = 19.99 * 100;

System.out.println(d);// 1998.9999999999998

System.out.printf("%1.0f\n", d); // 1999

~

yawmarka at 2007-7-8 23:50:08 > top of Java-index,Java Essentials,New To Java...
# 4
Thanks for the reply. Can you shed anylight on why 19.99 * 100 = 19.9999999999998?
jmmorina at 2007-7-8 23:50:08 > top of Java-index,Java Essentials,New To Java...
# 5

> Thanks for the reply. Can you shed anylight on why

> 19.99 * 100 = 19.9999999999998?

[url=http://en.wikipedia.org/wiki/Floating_point]Floating point - From Wikipedia, the free encyclopedia[/url]

[url=http://java.sun.com/developer/JDCTechTips/2003/tt0204.html#2]Some things you should know about floating-point arithmetic[/url]

[url=http://docs.sun.com/source/806-3568/ncg_goldberg.html]What Every Computer Scientist Should Know About Floating-Point Arithmetic[/url]

~

yawmarka at 2007-7-8 23:50:08 > top of Java-index,Java Essentials,New To Java...