-1

I created this simple coin conversion, but for some reason my print output is acting weird, should't it output 12995?

This is my code:

public static void main(String[]args)
{
    double x=129.95;
    int y= (int)(x*100);
    System.out.println(y);
}

Output : 12994

Niloy Alam
  • 23
  • 2
  • Welcome to StackOverFlow. Please respect the rules to post http://stackoverflow.com/help/how-to-ask For instance, do not put "Urgent" in your title, this is very aggressive. Then your code is not documented, and the informations given are not enough. – Cukic0d Sep 22 '16 at 20:36
  • For a more technical writeup: [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – azurefrog Sep 22 '16 at 20:42
  • It did't took long to find this: http://stackoverflow.com/questions/13467849/double-multiplied-by-100-and-then-cast-to-long-is-giving-wrong-value – Xen Sep 22 '16 at 20:47
  • 1
    This may be a bit irrelevant, but why is question getting thumbs down, I understand stackoverflow is filled professional consultants, but doesn't this sort of demotivate to ask us questions. – Niloy Alam Sep 22 '16 at 20:49
  • It's a cultural thing. It didn't used to be so. – Mick Sep 22 '16 at 20:57
  • 1
    Thank you for all the help. I am of low income, it means a lot to me that I can reach out to your professionals.I am thankful for your generoousity. – Niloy Alam Sep 22 '16 at 20:59
  • 1
    Don't give up on the site. You will get help with genuine problems. – Mick Sep 22 '16 at 21:08

1 Answers1

0

Using Math.round will give you your expected answer. You can refer to the comments on your post for more information regarding floating points.

public static void main(final String[] args) {
    double x = 129.95;
    int y = (int) Math.round(x * 100);
    System.out.println(y);
}
Aelexe
  • 1,216
  • 3
  • 18
  • 27