• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

dividing int and creating Double?

 
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I have this formula which divides an int by int and then multiplies it by 0.3, the I save this in variable "fre". according to my calculator variable fre should be 0.2, but my program returns 0.19999999999999998. I dont know what am I doing wrong?

variables values are:
freqValue:2
maxFreqInPage:3

and here is the code snippet:

I have converted the ints to doubles.

Thank you!
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your calculator probably comes up with the same value as Java, or one like it, but just rounds it before displaying.

The short version is this: It's impossible to exactly represent 0.2 in a double, for basically the same reason that it's impossible to represent 1/3 in a finite number of digits in base-10.

Longer version: What Every Computer Scientist Should Know About Floating-Point Arithmetic, by David Goldberg.

If you want it to display with less precision, you can use one of the following:
  • java.text.DecimalFormat
  • String.format()
  • System.out.printf() (which calls String.format())

  •  
    sahar eb
    Ranch Hand
    Posts: 38
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Thanks Jeff Verdegan! then I guess my code is fine!
     
    With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    reply
      Bookmark Topic Watch Topic
    • New Topic