• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Favouring Integer for addition calculations rather than BigDecimal- precision of addition using int

 
Amandeep Singh
Ranch Hand
Posts: 850
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am getting result of -1,1,0 as a result of compare operation.

Now i want to add this value to db column value, as the above value is in int type thats why now using the Integer.

SnapShot of the code:


Question: Is doing addition operations recommended through int rather than BigDecimal because it will not loose its precision ?

Question: does intValue() loose it precision after certain range.

if not i can change the above code to like this.
 
Rob Spoor
Sheriff
Pie
Posts: 20393
46
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All integer types (byte, char, short, int and long) never lose any precision, but they have limited range. If this is not going to be a problem using ints or longs is just fine.
 
Amandeep Singh
Ranch Hand
Posts: 850
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
will they loose precision after the limited range. so how much is the limited range?
 
Paul Clapham
Sheriff
Pie
Posts: 20203
26
MySQL Database
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm pretty sure the API documentation tells you what the value of (for example) Integer.MAX_VALUE is.
 
W. Joe Smith
Ranch Hand
Posts: 710
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Amandeep Singh wrote:will they loose precision after the limited range. so how much is the limited range?


If you try to assign a value to a primitive type that is out of its range the JVM will yell at you. You can't assign a value to a primitive that is outside of its range unless you explicitly cast it to the desired type, but it will result in loss of precision.
 
Rob Spoor
Sheriff
Pie
Posts: 20393
46
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you add an int to an int, and the resulting value would become larger than Integer.MAX_VALUE, it will wrap - becoming negative. If you believe this is a possibility, use long. If the same issue can occur for long (becoming larger than Long.MAX_VALUE), BigInteger and BigDecimal are the only options.
 
Amandeep Singh
Ranch Hand
Posts: 850
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well i will go with BigDecimal. Integer.Max_value has a limit of 2147483647.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic