Method: Decimal#add

Defined in:
lib/decimal/decimal.rb

#add(other, context = nil) ⇒ Object

Addition



1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
# File 'lib/decimal/decimal.rb', line 1417

def add(other, context=nil)

  context = Decimal.define_context(context)
  other = _convert(other)

  if self.special? || other.special?
    ans = _check_nans(context,other)
    return ans if ans

    if self.infinite?
      if self.sign != other.sign && other.infinite?
        return context.exception(InvalidOperation, '-INF + INF')
      end
      return Decimal(self)
    end

    return Decimal(other) if other.infinite?
  end

  exp = [self.exponent, other.exponent].min
  negativezero = (context.rounding == ROUND_FLOOR && self.sign != other.sign)

  if self.zero? && other.zero?
    sign = [self.sign, other.sign].max
    sign = -1 if negativezero
    ans = Decimal.new([sign, 0, exp])._fix(context)
    return ans
  end

  if self.zero?
    exp = [exp, other.exponent - context.precision - 1].max unless context.exact?
    return other._rescale(exp, context.rounding)._fix(context)
  end

  if other.zero?
    exp = [exp, self.exponent - context.precision - 1].max unless context.exact?
    return self._rescale(exp, context.rounding)._fix(context)
  end

  op1, op2 = _normalize(self, other, context.precision)

  result_sign = result_coeff = result_exp = nil
  if op1.sign != op2.sign
    return ans = Decimal.new([negativezero ? -1 : +1, 0, exp])._fix(context) if op1.coefficient == op2.coefficient
    op1,op2 = op2,op1 if op1.coefficient < op2.coefficient
    result_sign = op1.sign
    op1,op2 = op1.copy_negate, op2.copy_negate if result_sign < 0
  elsif op1.sign < 0
    result_sign = -1
    op1,op2 = op1.copy_negate, op2.copy_negate
  else
    result_sign = +1
  end

  if op2.sign == +1
    result_coeff = op1.coefficient + op2.coefficient
  else
    result_coeff = op1.coefficient - op2.coefficient
  end

  result_exp = op1.exponent

  return Decimal([result_sign, result_coeff, result_exp])._fix(context)

end