-1

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

Michael M.
  • 10,486
  • 9
  • 18
  • 34

1 Answers1

0

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);
sm3sher
  • 2,764
  • 1
  • 11
  • 23
  • Isn't BigDecimal an overkill for this? A simple `double` would do the job right? – lifetimeLearner007 Apr 28 '23 at 05:16
  • 1
    When dealing with monetary values, it is generally recommended to use `BigDecimal` instead of `double` to avoid precision errors that may arise due to the binary representation of floating-point numbers. – sm3sher Apr 28 '23 at 06:32
  • I used Long while storing the value because of there are some values in millions will it store those values too...? – Amit Singh May 02 '23 at 16:29
  • `Long` only goes until 64-bit, `BigDecimal` follows arbitrary precision and will get as large as possible until your computer runs out of memory. In general you can store much higher values than just a few millions when using `BigDecimal`. – sm3sher May 03 '23 at 06:55