Why NOT to Use 'float' or 'double' Types in Groovy

The types 'float' and 'double' should not be used in Groovy because the result of the logic element can ultimately end up in a 'double' which is currently serialized in JSON as a string. Therefore ensure you use 'BigDecimal' whenever dealing with a decimal point number and force the type when initially getting data back from a function call.

You can do this as follows:

num1.toBigDecimal()

As you can see in the Groovy documentation, there are situations where a mathematical operation between 2 different types can result in a third type. For example, a BigDecimal multiplied by a Float will end up in a Double!

Extract from the Groovy documentation:

Also, there are situations in Groovy that will generate a 'double', for example the 'power of' operation:

So if you do such an operation, you should perform a conversion to 'BigDecimal' afterwards. A 'double' value which is serialized to text can have an unexpected impact; for example in a normal export to Excel where these values may not be recognized correctly depending on the user locale.

Found an issue in documentation? Write to us.