• Post Reply Bookmark Topic Watch Topic
  • New Topic

help with double  RSS feed

 
mike cool
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • 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
 
todd runstein
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • 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.
 
Rob Spoor
Sheriff
Posts: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • 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.
 
vivien siu
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!