Monday, 15 April 2013

java - BigDecimal operations precision overflow -



java - BigDecimal operations precision overflow -

import java.math.bigdecimal; public class testnumber { public static void main(string[] args) { bigdecimal bd = new bigdecimal(0); bd = bd.add(new bigdecimal(19.89)); system.out.println(bd.doublevalue() + " - \t " + bd); } }

i have multiple biddecimals fields , arithmetic operations/comparations, problem arithmetic results , decimals values.

for above illustration output follows:

19.89 - 19.8900000000000005684341886080801486968994140625

i expects:

19.89

the unexpected result creates other undesirable outputs perform operations on field type bigdecimal

the double value displayed println not same actual value stored in double variable.

in range there infinite number of real numbers finite number of representable floating point values. when define floating point value, value may not map representable floating point value, in case representable value closest want. (also maintain in mind representation in binary, , lot of numbers familiar become repeating decimals in binary have truncated.) here of course of study it's off 0.0000000000000005684341886080801486968994140625.

the lines

double d = 19.89d; system.out.println(d);

will show cleaned-up approximation of what's in d. java hiding messy trailing decimals you.

on other hand, these lines

double d = 19.89d bigdecimal b = new bigdecimal(d); system.out.println(b);

result in bigdecimal getting initialized entire contents of d, bigdecimal reproduces faithfully out lastly trailing digit.

when println passed bigdecimal, bigdecimal's tostring method returns string showing digits stored, , println writes string console.

using

bigdecimal b = new bigdecimal("19.89");

will result in actual decimal value 19.89 getting stored in bigdecimal, because no floating point evaluation involved.

java math bigdecimal

No comments:

Post a Comment