|
Well, not exactly. Your "average" doesn't become 4.22, it becomes something that's extremely close to 4.22. Floating point numbers can't express *any* fraction exactly unless it's a power of 0.5. So don't be surprised if you do "System.out.println(average)" and you find something like "4.2200000000033775" appearing. That was the problem experienced in the original post, I believe. You can mask the problem by using a DecimalFormat object to display the number, or you can use BigDecimal objects, but in either case you may get burned by rounding that you didn't expect. (BigDecimal provides a half-dozen different ways to round.) In commercial work this isn't likely to be much of a problem, but in scientific work it can be, and there's a whole field of mathematics devoted to this kind of thing. PC2 -----Original Message----- From: James Donkin [mailto:James@DuMaurier.co.uk] Sent: March 1, 2001 05:49 To: JAVA400-L@midrange.com Subject: Re: Decimal rounding of a float data type in Java. </snip> One way for getting rid of the rounding problem would be to... float roundedInt = Float.parseFloat(twoDigits.format( average )); Or you could... int temp = (int)(average * 100); average = (float)temp / 100; e.g. average = 4.222222222222 temp then = 422 average then becomes 4.22 </snip> +--- | This is the JAVA/400 Mailing List! | To submit a new message, send your mail to JAVA400-L@midrange.com. | To subscribe to this list send email to JAVA400-L-SUB@midrange.com. | To unsubscribe from this list send email to JAVA400-L-UNSUB@midrange.com. | Questions should be directed to the list owner: joe@zappie.net +---
As an Amazon Associate we earn from qualifying purchases.
This mailing list archive is Copyright 1997-2024 by midrange.com and David Gibbs as a compilation work. Use of the archive is restricted to research of a business or technical nature. Any other uses are prohibited. Full details are available on our policy page. If you have questions about this, please contact [javascript protected email address].
Operating expenses for this site are earned using the Amazon Associate program and Google Adsense.