• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

BigDecimal wrong value?

 
Jack Deli
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When trying to make a simple converting program in Android I came across an issue with BigDecimal. My code below...

I try to multiply a number given by the user: for example 50.0 and I am supposed to get 1.64041994749999989200439642900164471939206123352050781250 but instead I get 164.0419947500..WHY? I do have a lot of if statements, meaby that's the problem? I tried searching the internet but couldn't find any solution to my problem.



Thanks in advance!
Blookiev123
 
harshvardhan ojha
Ranch Hand
Posts: 157
1
Android Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jack,

You are using String constructor of BigDecimal which is good, if you want to get the expected result use double constructor.

number = number.multiply(new BigDecimal(0.03280839895));

Please go through documentation for more info on predictability of values passed to different constructors.
 
Winston Gutkowski
Bartender
Pie
Posts: 10430
63
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jack Deli wrote:I try to multiply a number given by the user: for example 50.0 and I am supposed to get 1.64041994749999989200439642900164471939206123352050781250 but instead I get 164.0419947500..WHY?

I suspect that Harshvardhan is right; however, you are doing things properly and your answer is correct; so why would you imagine that you're 'supposed to get' a wrong answer?

Winston
 
Campbell Ritchie
Sheriff
Pie
Posts: 49472
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is something not quite right about your if statements. I suspect you have a very large block of if-elses. I would suggest you create yourself a Map which contains the values. So you could have "Galileo→Foot/square second" mapping to new BigDecimal("0.03280839895"), etc. You would obviously have to populate the Map beforehand, but you are already creating all those objects, You would also have to use the values from the spinners to create the keys. You would also be able to block nonsense conversions like inch to kg/sqcm. In that case you would get null out of the Map.

And everybody is right: 1.6404199475 is in fact what you get from 50×0.03280839895. But you would appear to have acquired two extra 0s somewhere to get 164.0419947500! Try printing the number value before the calculations. Because you are doing arithmetic on number, it is conceivable that you are changing it to 5000 without noticing. And number is hardly a good name for a variable. Try changing to a two variables, maybe called input and result.

Are you actually using spinners to hold those values? I thought spinners only returned numbers.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic