0

I'm using a fraction to add to the current BigDecimal. It keeps returning an int. Not sure what I'm doing wrong.

//within a class function    
public BigDecimal result  = new BigDecimal(1);
int x = 2;
double g = 1/x;
result = result.add(new BigDecimal(g));
String s = result.toString();
System.out.println(s);
JCoder
  • 189
  • 1
  • 3
  • 17

1 Answers1

2

You have to do the following:

BigDecimal result = new BigDecimal(1);
int x = 2;
double g = 1.0 / x;  //<---------- 1.0
result = result.add(new BigDecimal(g));
String s = result.toString();
System.out.println(s);

then there will be a double as outcome

griFlo
  • 2,084
  • 18
  • 28
  • I executed the exact code in a Testclass. The result is 1.5. Have you tried the exact same code? Whats your result? – griFlo Feb 18 '15 at 08:44
  • Replaced toString() with format(). However, instead 2.xxxxxx, I am getting 2.000000.... An int followed by a decimal and zeros, not a BigDecimal as a string. – JCoder Feb 18 '15 at 19:56
  • Sorry, I don't get your point. where do you want to get "2.0000..."? The outecome should be 1.5. And a BigDecimal doesnt have a "format()" Method. (You said you replaced toString() with format()) or maybe I'm getting this wrong ... – griFlo Feb 19 '15 at 07:46