javascriptgroovygroovyscriptengine

Unable to add Long values in Groovy


Unable to add Long values in Groovy. When we sum, it is not adding value after decimal.

  Long val1 = makeNullZero(getCustomFieldValue('Benefit 1 Annual $'));
  Long val2 = makeNullZero(getCustomFieldValue('Benefit 2 Annual $'));
  Long val3 = makeNullZero(getCustomFieldValue('Benefit 3 Annual $'));
  Long val4 = makeNullZero(getCustomFieldValue('Benefit 4 Annual $'));
  Long val5 = makeNullZero(getCustomFieldValue('Estimated Development Cost $'));

  BigDecimal sum = (val1 + val2 + val3 + val4) / val5 
  return sum.round(2);

When we sum = (2.5 + 2.5 + 2.5 + 2.5), getting 8. It should be 10

sum = (2.5 + 2.5 + 2.5 + 2.5) / 3

Getting 2.67, it should be 3.33

when we sum, it is not adding value after decimal. getting 8, it should be 10


Solution

  • The datatype Long truncates 2.5 into 2, resulting in 2 + 2 + 2 + 2 = 8.

    Try storing your values in BigDecimal:

    BigDecimal val1 = makeNullZero(getCustomFieldValue('Benefit 1 Annual $'));
    BigDecimal val2 = makeNullZero(getCustomFieldValue('Benefit 2 Annual $'));
    BigDecimal val3 = makeNullZero(getCustomFieldValue('Benefit 3 Annual $'));
    BigDecimal val4 = makeNullZero(getCustomFieldValue('Benefit 4 Annual $'));
    BigDecimal val5 = makeNullZero(getCustomFieldValue('Estimated Development Cost $'));
    

    I would also suggest using add and divide since this way you gain more control over precision and rounding:

    BigDecimal sum = val1.add(val2).add(val3).add(val4).divide(val5, 2, RoundingMode.HALF_UP);