2017-07-16 2 views
-2

Besoin de quelques suggestions sur un comportement étrange en ajoutant un double avec SEULEMENT 0.39 (nombre étrange). extrait a d'abord bon exemple avec 0,38 et le second avec 0,39Ajout de 0.39 Double variable en Java

// 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 

Répondre

1

Lorsque vous utilisez BigDecimal, vous souhaitez utiliser la version qui prend String. Si vous utilisez double, alors vous avez déjà perte de précision.

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

qui sort (comme prévu)

2618.38 

et pour 2618.39

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

mais, si vous avez besoin d'utiliser double, vous pourriez choisir d'utiliser sortie formatée (qui va et pour vous) comme

double[] premiums = { 1031.38, 1031.39 }; 
double netToCompany = 1587.0; 
for (double premium : premiums) { 
    System.out.printf("%.2f%n", premium + netToCompany); 
} 
+0

Merci et je suis au courant de la mise en forme mais je ne devrais pas selon needm La question est pour seulement 0.39 pourquoi obtenons-nous 2618.3900000000003. Le long 000 après la virgule. Cela n'arrive pas pour n'importe quel nombre d'otjer. Fera le format si je n'ai pas le choix comme suggéré. Thx –

+0

@ N.Murali [smbc - '0.1 + 0.2'] (http://www.smbc-comics.com/?id=2999) –