Path: csiph.com!aioe.org!.POSTED!not-for-mail From: =?UTF-8?Q?Arne_Vajh=c3=b8j?= Newsgroups: comp.lang.java.programmer Subject: Re: [OT] Re: missing import java.lang.Comparable Date: Mon, 11 Jul 2016 22:13:39 -0400 Organization: Aioe.org NNTP Server Lines: 71 Message-ID: References: <128e7e20-d311-413d-abbc-e885b34ae402@googlegroups.com> <87dc5bee-f689-4f2e-90a8-a43a2de9fe49@googlegroups.com> <638a1d64-f125-4456-a20b-4dbf45f49da2@googlegroups.com> <60a5ccde-2657-48d6-b3dd-04ec1a0973ab@googlegroups.com> <6f69c451-849d-4672-9025-7880a62bd72d@googlegroups.com> NNTP-Posting-Host: 7SK6yTFfqwlIPNBLl3l7Qg.user.gioia.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 8bit X-Complaints-To: abuse@aioe.org User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Thunderbird/45.2.0 X-Notice: Filtered by postfilter v. 0.8.2 Xref: csiph.com comp.lang.java.programmer:34865 On 7/11/2016 8:30 AM, Eric Douglas wrote: > On Friday, July 8, 2016 at 8:32:14 PM UTC-4, Arne Vajhøj wrote: >> I don't think this example shows what you think it shows. >> >> It really shows that String.valueOf has an impact on the result. > > Converting to a String is what makes it work. String.valueOf "round off" a little bit in the string result. But I would not consider that a general solution. > Whether it's the financial application dealing with fractions of > pennies or an inventory management application which may have > fractions depending on the unit of measure, I expect .0001 + .0002 to > get exactly .0003. Then you better use a data type that has this characteristic. Use BigDecimal not double. > > Code: > DecimalFormat myFormatter = new DecimalFormat("0.####################"); > String output; > double a = .0002; > double b = .0001; > output = myFormatter.format(a + b); > System.out.println(output); > BigDecimal bda = new BigDecimal(String.valueOf(a)); > BigDecimal bdb = new BigDecimal(String.valueOf(b)); > bda = bda.add(bdb); > output = myFormatter.format(bda.doubleValue()); > System.out.println(output); > Output: > 0.00030000000000000003 > 0.0003 > > Code: > DecimalFormat myFormatter = new DecimalFormat("0.####################"); > String output; > double a = .0002; > double b = .0001; > output = myFormatter.format(a + b); > System.out.println(output); > BigDecimal bda = new BigDecimal(a); > BigDecimal bdb = new BigDecimal(b); > bda = bda.add(bdb); > output = myFormatter.format(bda.doubleValue()); > System.out.println(output); > Output: > 0.00030000000000000003 > 0.00030000000000000003 Yes. But I think you want to do this: DecimalFormat fmt = new DecimalFormat("0.####################"); BigDecimal bda = new BigDecimal("0.0002"); BigDecimal bdb = new BigDecimal("0.0001"); BigDecimal bdc = bda.add(bdb); System.out.println(bdc); System.out.println(fmt.format(bdc)); 0.0003 0.0003 Arne