-2

Need few suggestions on a strange behavior in adding a double with ONLY 0.39 (strange number). First snippet has proper example with 0.38 and the second with 0.39

// code snippet 1 : Adding xxxx.38 to xxxx.00

double b =1031.38;
double a =1587.00;
System.out.println ("using double     "+(a+b));

BigDecimal premium = BigDecimal.valueOf(a);
BigDecimal netToCompany = BigDecimal.valueOf(b);
double result =Double.parseDouble(premium.add(netToCompany).toString());
System.out.println("using BigDecimal "+result);

// correct Output xxxx.38 + xxxx.00 = xxxx.38

using double     2618.38
using BigDecimal 2618.38

***** ------------------------------ ******

// code snippet 2 : Adding xxxx.39 to xxxx.00

double b =1031.39;
double a =1587.00;
System.out.println("using double     "+(a+b));

BigDecimal premium = BigDecimal.valueOf(a);
BigDecimal netToCompany = BigDecimal.valueOf(b);
double result =   Double.parseDouble(premium.add(netToCompany).toString());

// wrong Output xxxx.39 + xxxx.00 = xxxx.3900000000003

using double  2618.3900000000003
using BigDecimal 2618.39

1 Answers1

1

When you use BigDecimal, you want to use the version that takes a String. If you use double, then you have already lost precision.

BigDecimal premium = new BigDecimal("1031.38");
BigDecimal netToCompany = new BigDecimal("1587.00");

Which outputs (as expected)

2618.38

and for 2618.39

BigDecimal premium = new BigDecimal("1031.39");
BigDecimal netToCompany = new BigDecimal("1587.00");
System.out.println(premium.add(netToCompany));

but, if you need to use double, you might choose to use formatted output (which will round for you) like

double[] premiums = { 1031.38, 1031.39 };
double netToCompany = 1587.0;
for (double premium : premiums) {
    System.out.printf("%.2f%n", premium + netToCompany);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Thanks and i am aware of formatting but i should not as per needm The question is for only 0.39 why are we getting 2618.3900000000003. The long 000s after decimal. Doesn't happen for any otjer numbers. Will do format if i have no choice as suggested. Thx – N.Murali Jul 16 '17 at 06:23
  • @N.Murali [smbc - `0.1 + 0.2`](http://www.smbc-comics.com/?id=2999) – Elliott Frisch Jul 16 '17 at 06:27