JAXB, BigDecimal or double?

I work on various web services and I always use WSDL First.

JAXB generates a type type:

<xsd:simpleType name="CurrencyFormatTyp"> <xsd:restriction base="xsd:decimal"> <xsd:totalDigits value="13"/> <xsd:fractionDigits value="2"/> <xsd:minInclusive value="0.01"/> </xsd:restriction> </xsd:simpleType> 

Java binding type BigDecimal (as mentioned in the JAXB specification).

When I then perform some simple arithmetic operation with values ​​of type double (which are stored in the database and mapped to the type double by hibernation), I run into problems.

 <ns5:charge>0.200000000000000011102230246251565404236316680908203125</ns5:charge> <ns5:addcharge>0.0360000000000000042188474935755948536098003387451171875</ns5:addcharge> <ns5:tax>0.047199999999999998900879205621095024980604648590087890625</ns5:tax> <ns5:totalextax>0.2360000000000000153210777398271602578461170196533203125</ns5:totalextax> 

What will be the right way?

  • Convert all my values ​​to double (JAXB binding from BigDecimal to double )
  • Display hibernation double to BigDecimal

and perform all my arithmetic operations in one type of objects.

+4
source share
2 answers

You never want to use floating point formats (for example, double and float in Java) for currency transactions, because they have limited accuracy and were designed to store values ​​that are somehow derived from the dimension (in this case, they’re not quite accurate to begin with, in which case limited accuracy is not a problem).

What every computer scientist needs to know about floating point arithmetic is an article on this topic. It's a little math-heavy, but it really helps to figure it out (alternatively, an article related to Michael Borgwardt is much easier to understand and still demonstrates / explains the problem).

To avoid such problems, make sure that you use BigDecimal exclusively in your code and that all external storage / transfer points use fixed / arbitrary precision values ​​(i.e. your database also should not store floating point numbers).

+10
source
  • Read the floating point guide
  • Never use double or float for cash
  • Use BigDecimal instead, what exactly is this for
+7
source

Source: https://habr.com/ru/post/1309309/


All Articles