Precision and scale in BigDecimal and MathContext

Lately, after publishing the previous post, a friend of mine passed me a snipped of BigDecimal code. He was wondering, why the following execution: BigDecimal a = new BigDecimal(2.9); BigDecimal b = new BigDecimal(4000); MathContext mc = new MathContext(2, RoundingMode.HALF_DOWN); BigDecimal r1 = a.multiply(b, mc); BigDecimal r2 = a.multiply(b).setScale(2, RoundingMode.HALF_DOWN); System.out.println("r1 = " + r1); System.out.println("r2 = " + r2); is returning different values for r1 and r2: r1 = 1.2E+4 r2 = 11600.00 Well, at first glance it seems that r1 differs from r2 in only one thing: the r1 is using RoundingMode through MathContext object, while the r2 is using the RoundingMode through setScale(-) method. ...

February 5, 2011 · 2 min

Float and double in Java "inaccurate" result

There is a well known problem with precise floating point numbers representation in a computer, and Java is no different in this case. If you want to see it for yourself, than try executing the below code: Double d = new Double(4.395f); System.out.println(d); You might expect the 4.395 will be printed out, right? Well, you’re defining an “exact” number as a float (32 bit), than casting it to the double (64 bit) so there should be no problem, as it shouldn’t affect the value. After all it’s only 4.395 and not 4.3956312123540604, right? In the matter of fact, the result will be like this: ...

February 4, 2011 · 3 min