Firstly, you "lost" the decimal part in the very first
line of your code. Your first println should print the
decimals.
As far
as I can see (jdk1.4 - perhaps it's different in 1.5) BigDecimal does not have a
constructor that takes a float as an argument.
All of
these will work:
BigDecimal db = new
BigDecimal("10099999.0499");
or
BigDecimal db = new
BigDecimal(BigInteger.valueOf(100999990499L), 4);
or
or
BigDecimal db = new BigDecimal((double)
10099999.0499);
-----Original Message-----Hi all
From: [email protected] [mailto:[EMAIL PROTECTED]On Behalf Of Carl Woermann
Sent: 19 October 2006 09:34
To: [email protected]
Subject: [CTJUG Forum] Java Float formatting
Ive been getting funny bugs with formatting floats, having to round them according to unconventional rules etc, so after some googling I decided to use Big Decimal, which apparentlay makes it all good. To my surprise I started getting the same errors. So I've narrowed the source of all problems down to this a strange oddity with is best illustrated in the code below:
BigDecimal db = new BigDecimal(10099999.0499f);System.out.println("db: " + db); // prints: db: 10099999
BigDecimal whole = db.setScale (0, BigDecimal.ROUND_FLOOR); // does not modify original value according to javadoc
System.out.println("Whole: " + whole); // prints: Whole: 10099999
BigDecimal remainder = db.subtract (whole); // should leave me with 0.049...
System.out.println("Remainder: " + remainder ); // prints: Remainder: 0
// See if it is really ZeroSystem.out.println("Compare: " +remainder.compareTo(new BigDecimal(0))); // prints Compare: 0
// So where is my fraction of 0.0.49 gone?Note that the above code behave as expected if you lower the number eg 9999.049f - I haven't bothered to try to find the exact number at which it breaks, and a check if the float is bigger that Float.MaxValue also passes.
Anybody wrote any accounting or banking app lately? ( My mind wanders to apps deployed in Zim for example.. )
Thanks - Carl
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "CTJUG Forum" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at http://groups.google.com/group/CTJUG-Forum
For the ctjug home page see http://www.ctjug.org.za
-~----------~----~----~----~------~----~------~--~---
This e-mail and any files transmitted with it are confidential and intended solely for the use of the individual or entity to which they are addressed. If you have received this e-mail in error please notify NSFAS immediately. Please note that any views or opinions presented in this e-mail are solely those of the author and do not necessarily represent those of the organisation.
