Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

lilstevey (4628)

  (email not shown publicly)

  • Heinekin
  • Kro
  • Addlestones
  • Old Rosie
  • Thatchers
  • Strongbow
  • Erdinger
  • Guiness
  • Budvar
  • Leffe ( usually blond )
  • Various Real Ales when in premises suitable

Journal of lilstevey (4628)

Tuesday February 20, 2007
07:03 AM

Magic Magic Java

[ #32449 ]
I do like a lot of things about the java language, however occasionally it does things that I do consider counter intuitive. Consider the following line of code:

BigDecimal result = new BigDecimal(10).divide(new BigDecimal(3));

Given appropriatte imports, by looking at the code I would not be at all suprised to see any of the following values stored in result:
  • 4
  • 3
  • 3.33
  • 3.33334
  • 3.333333

I find the actual output slightly outside of my predicted pool of predicted behavour:

Exception in thread "main" java.lang.ArithmeticException : Non-terminating decimal expansion; no exact representable decimal result. The logic thing to me given the operation would be to use defaults ( preferably controllable ones ), not to produce occasional errors that can confuse hell out of a beginner.

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
More | Login | Reply
Loading... please wait.
  • to be fair, this behavior is in the Javadocs :-)

    I'm ambivalent about implementing defaults. I think one of the reasons you use a BigDecimal over a float is that you want precision, like when manipulating money. Forcing you to then specify that precision (with a scale and rounding mode) isn't that far out of bounds.

    But you're right that beginners might not be aware of these trade-offs. Maybe they're just grabbing numberic fields out of a database and they're automatically mapped to BigDecimals...

    • it's taken a while for me to respond to your post, sorry. I can only assume my revision overtook all other things java in my mental priority list for a bit

      You have a very good point, it is in the javadocs, and in regards to precision, obviously anyone would need several landfill sites worth of justification for opting for a float for a decimal for currency, and there's additional concerns where countries like Mauritania and Madagascar are concerned ( Or at least I suspect there may be, given wikipedias