[rules-users] [rules user] different behavior on double type

Wolfgang Laun wolfgang.laun at gmail.com
Tue Mar 27 03:15:17 EDT 2012


On 27/03/2012, Zeke <xanadu860122 at gmail.com> wrote:
> Whether the comparison is precarious or not should depend on how you handle
> the literal. If you handle 99.9 as BigDecimal("99.9") which precision can
> be controlled, you can trust the comparison.
>

Wait a sec: primarily, you are testing a double, and this is where
some unavoidable imprecision is introduced. These are some doubles
close
to 99.9:

a     99.899999999999990000 0x1.8f99999999999p6
b     99.900000000000000000 0x1.8f9999999999ap6
c     99.900000000000020000 0x1.8f9999999999bp6

a < 99.9 is the true value truncated, b > 99.9 is rounded  (the next
binary digit being 1). There just isn't a double == 99.9. (Don't be
confused by b's printed value.)

The BigDecimal value 99.90000000000001 you have observed is due to
rounding the result of new BigDecimal( (double)99.9 ), i.e.
    99.900000000000005684341886080801486968994140625

It's easy to see that a better value is obtained by using a String value:
    new BigDecimal( "99.9" )
but I don't know whether your Drools version would let you write
doubleValue == "99.9".


If you want/have to stick with 4.x you might use public static final
doubles defined in some Java class instead of the magic 99.9. This
should avoid the sidestep into BigDecimal and the ensuing conversion
confusion.

-W



More information about the rules-users mailing list