• 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

help with double

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hey

double d1 = 5555.55;
double d2 = 1111.11;

if i subtract d2 from d1

double d3 = d1 - d2;

the result will be : Sub is: 4444.4400000000005 ;

how can i control the decimal amount for example i want have only 3
digits after the dot Sub is: 4444.440
but not using output format
i try bigDecimal , math class but i couldn't find the solution
any idea
 
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ain't floating point math great?

I just ran into this and used NumberFormat to solve this (another advantage in my case was that I got a String, which is what I utimately needed). You can set the min and max number of decimal spaces. May not be the best way, but it works.
 
Sheriff
Posts: 22787
131
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just as 1/3 cannot be written within a finite number of numbers, computers face the same problem. However, computers can only exactly store fractions that have only powers of 2 in them:
x1 * 1/2 + x2 * 1/4 + x3 * 1/8 + ....
Even something as simple as 1/10 (0.1) cannot be stored exactly because it has a repetitive part:
1/10 = 1/16 + 1/32 + 1/256 + 1/512 + 1/4096 + ...

Which is in binary 0.000110011001100110011001100...
Somewhere, this gets rounded of course which leads to little differences with what you expect.
 
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
you need to use the API DecimalFormat. Create a new object of type DecimalFormat and declare the decimal places you need. Like mine I declare up to 3 decimal places. Then use the format() method to format the d3 variable.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic