예제 #1
0
  private static BigDecimal getConvertedAmountFromHighToLow(
      AreaEnum sourceType, AreaEnum targetType, BigDecimal amount) {
    BigDecimal updatedAmount = null;
    BigDecimal tmp = SQ_MILE_TO_SQ_KM.multiply(AreaEnum.SQ_YARD.getUpperToLowerVal());

    if (sourceType == targetType) {
      return amount;
    }
    if (isCommonRuleApplicable(sourceType, targetType)) {
      updatedAmount = getCommonConvertedAmountFromHighToLow(sourceType, targetType, amount);
      return updatedAmount.abs(Constant.MC);
    }
    if (sourceType == AreaEnum.SQ_MILE) {
      updatedAmount = amount.multiply(SQ_MILE_TO_SQ_KM);
    } else if (sourceType == AreaEnum.SQ_YARD) {
      updatedAmount = amount.multiply(SQ_YARD_TO_SQ_KM);
    } else if (sourceType == AreaEnum.SQ_FOOT) {
      updatedAmount = amount.multiply(SQ_FT_TO_SQ_KM);
    } else if (sourceType == AreaEnum.SQ_INCH) {
      updatedAmount = amount.multiply(SQ_INCH_TO_SQ_KM);
    }
    updatedAmount =
        getCommonConvertedAmountFromHighToLow(AreaEnum.SQ_KM, targetType, updatedAmount);
    return updatedAmount.abs(Constant.MC);
  }
예제 #2
0
 // 密码加密
 private static String Encryption(String oldPwd) {
   String newPwd = "0";
   BigDecimal oldPwdBD = new BigDecimal(oldPwd);
   BigDecimal tempYPwd = oldPwdBD.multiply(new BigDecimal("135791"));
   int tempYPwdLen = tempYPwd.toString().length();
   String tempTPwd = "";
   if (tempYPwdLen >= 12) {
     tempTPwd = tempYPwd.toString().substring(1, 7);
   } else if (tempYPwdLen < 12 && tempYPwdLen >= 5) {
     tempTPwd = tempYPwd.toString().substring(0, tempYPwd.toString().length() - 5);
   } else {
     tempTPwd = tempYPwd.toString();
   }
   BigDecimal tempTPwdBD = new BigDecimal(tempTPwd);
   BigDecimal tempZPwdBD = tempTPwdBD.add(oldPwdBD);
   if (tempZPwdBD.intValue() < 1000000) {
     tempZPwdBD = tempZPwdBD.subtract(new BigDecimal("135791"));
     newPwd = tempZPwdBD.abs().toString();
   } else {
     tempZPwdBD = tempZPwdBD.subtract(new BigDecimal("1000000"));
     tempZPwdBD = tempZPwdBD.subtract(new BigDecimal("135791"));
     newPwd = tempZPwdBD.abs().toString();
   }
   // 如果netPwd最后获取的是0,则加密后的密码为999888
   if (newPwd.equals("0")) {
     return "999888";
   } else {
     StringBuilder tempNewPwd = new StringBuilder();
     for (int x = 0; x < 6 - newPwd.length(); x++) {
       tempNewPwd.append("0");
     }
     tempNewPwd.append(newPwd);
     return tempNewPwd.toString();
   }
 }
  /**
   * @param minValue
   * @param maxValue
   * @param scale
   * @param isForFunctionalBin Functional bins should always be non-sci notation.
   * @return
   */
  public static DecimalFormat getFormat(
      BigDecimal minValue, BigDecimal maxValue, int scale, boolean isForFunctionalBin) {

    // Find number of digits left of decimal
    BigDecimal maxAbs = minValue.abs();
    maxAbs = maxAbs.max(maxValue.abs());
    int digitsLeftOfDecimal = Math.abs(maxAbs.precision() - maxAbs.scale());

    boolean useSciNotation = (digitsLeftOfDecimal > 4 || scale > 4) && !isForFunctionalBin;

    String formatStr = null;

    if (useSciNotation) {
      if (scale > 0) {
        // Sig figs beyond the decimal (decimal fraction number)
        formatStr = "0." + StringUtils.repeat("0", scale) + "E0";
      } else {
        // will contain no decimal number
        formatStr = "##0.##E0";
      }
    } else {
      if (scale > 0) {
        // Sig figs beyond the decimal (decimal fraction number)
        formatStr = "0." + StringUtils.repeat("0", scale);
      } else {
        // will contain no decimal number
        formatStr = "0";
      }
    }

    return new DecimalFormat(formatStr);
  }
예제 #4
0
    public final Row range(final BigDecimal aValue) {

      switch (type) {
        case E:
          final int tmpSignum = aValue.signum();
          if (tmpSignum == 1) {
            this.upper(this.getLowerLimit().add(aValue));
          } else if (tmpSignum == -1) {
            this.lower(this.getUpperLimit().add(aValue));
          }

          break;

        case L:
          this.lower(this.getUpperLimit().subtract(aValue.abs()));

          break;

        case G:
          this.upper(this.getLowerLimit().add(aValue.abs()));

          break;

        case N:
          this.level(null);
          this.weight(ONE);

          break;

        default:
          break;
      }

      return this;
    }
예제 #5
0
  private static BigDecimal getConvertedAmountFromLowToHigh(
      AreaEnum sourceType, AreaEnum targetType, BigDecimal amount) {
    BigDecimal updatedAmount = null;
    if (sourceType == targetType) {
      return amount;
    }
    if (isCommonRuleApplicable(targetType, sourceType)) {
      updatedAmount = getCommonConvertedAmountFromLowToHigh(sourceType, targetType, amount, amount);
      return updatedAmount.abs(Constant.MC);
    }
    // First convert everything to inch, the middle point
    if (sourceType == AreaEnum.SQ_CM) {
      updatedAmount = SQ_CM_TO_SQ_INCH;
    } else if (sourceType == AreaEnum.SQ_METER) {
      updatedAmount = Constant.TEN_THOUSAND.multiply(SQ_CM_TO_SQ_INCH);
    } else if (sourceType == AreaEnum.HECTARE) {
      updatedAmount = HECTRE_TO_SQ_INCH;
    } else if (sourceType == AreaEnum.SQ_KM) {
      updatedAmount = SQ_KM_TO_SQ_INCH;
    }

    updatedAmount = updatedAmount.multiply(amount);
    updatedAmount =
        getCommonConvertedAmountFromLowToHigh(AreaEnum.SQ_INCH, targetType, amount, updatedAmount);
    return updatedAmount;
  }
예제 #6
0
파일: DecBase.java 프로젝트: charleso/naca
  public static DecBase toDec(BigDecimal bd) {
    boolean bPositive = true;

    if (bd.signum() < 0) bPositive = false;

    String sValue = bd.abs().unscaledValue().toString();
    int nScale = bd.scale();
    if (sValue.length() > nScale) {
      String sInt = sValue.substring(0, sValue.length() - nScale);
      String sDec = sValue.substring(sValue.length() - nScale);
      DecBase dec = new DecBase(sInt, sDec);
      dec.setPositive(bPositive);
      return dec;
    } else {
      String sDec = new String();
      int nNbLeadingZeros = nScale - sValue.length();
      for (int n = 0; n < nNbLeadingZeros; n++) {
        sDec = sDec + "0";
      }
      sDec = sDec + sValue;

      DecBase dec = new DecBase(0, sDec);
      dec.setPositive(bPositive);
      return dec;
    }
  }
예제 #7
0
  public static BigDecimal get(final BigDecimal n) {

    // Make sure n is a positive number

    if (n.compareTo(ZERO) <= 0) {
      throw new IllegalArgumentException();
    }

    final BigDecimal initialGuess = getInitialApproximation(n);
    BigDecimal lastGuess = ZERO;
    BigDecimal guess = new BigDecimal(initialGuess.toString());

    // Iterate

    iterations = 0;
    boolean more = true;
    while (more) {
      lastGuess = guess;
      guess = n.divide(guess, scale, BigDecimal.ROUND_HALF_UP);
      guess = guess.add(lastGuess);
      guess = guess.divide(TWO, scale, BigDecimal.ROUND_HALF_UP);
      error = n.subtract(guess.multiply(guess));
      if (++iterations >= maxIterations) {
        more = false;
      } else if (lastGuess.equals(guess)) {
        more = error.abs().compareTo(ONE) >= 0;
      }
    }
    return guess;
  }
예제 #8
0
 /** Test for execute(). */
 @Test
 public void testExecute() {
   AbsoluteValueBigDecimal calc = new AbsoluteValueBigDecimal();
   BigDecimal input = new BigDecimal(-6).setScale(3);
   Object actual = calc.execute(input);
   Assert.assertEquals(input.abs(), actual);
 }
예제 #9
0
파일: Amount.java 프로젝트: kob-aha/gradle
 /** Returns a human consumable string representation of this amount. */
 public String format() {
   List<Units<Q>> allUnits = units.getUnitsForQuantity();
   BigDecimal base = normalised.abs();
   for (int i = allUnits.size() - 1; i >= 0; i--) {
     Units<Q> candidate = allUnits.get(i);
     if (base.compareTo(candidate.getFactor()) >= 0) {
       BigDecimal scaled = units.scaleTo(value, candidate);
       return String.format(
           "%s %s", new DecimalFormat("#.###").format(scaled), candidate.format(scaled));
     }
   }
   return String.format("%s %s", new DecimalFormat("#.###").format(value), units.format(value));
 }
예제 #10
0
 private void calTrendMaMonitor(
     TrendMaMonitor trendMaMonitor, Date date, BigDecimal prodPrice, BigDecimal maPrice) {
   if (trendMaMonitor.getCalDate() == null) {
     trendMaMonitor.setCalDate(date);
     trendMaMonitor.setProdPrice(prodPrice);
     trendMaMonitor.setMaPrice(maPrice);
     trendMaMonitor.setDiff(maPrice.subtract(prodPrice).divide(prodPrice, 4, RoundingMode.FLOOR));
     trendMaMonitor.setTrendDays(1);
   } else if (trendMaMonitor.getCalDate().before(date)) {
     BigDecimal lastDiff = trendMaMonitor.getDiff();
     BigDecimal diff = maPrice.subtract(prodPrice).divide(prodPrice, 4, RoundingMode.FLOOR);
     trendMaMonitor.setCalDate(date);
     trendMaMonitor.setProdPrice(prodPrice);
     trendMaMonitor.setMaPrice(maPrice);
     trendMaMonitor.setDiff(diff);
     if (diff.compareTo(BigDecimal.ZERO) == 0) {
       trendMaMonitor.setTrendDays(trendMaMonitor.getTrendDays() + 1);
       trendMaMonitor.setReturnDays(0);
     } else if (lastDiff.compareTo(BigDecimal.ZERO) == 0) {
       trendMaMonitor.setTrendDays(trendMaMonitor.getTrendDays() + 1);
       trendMaMonitor.setReturnDays(null);
     } else if (diff.compareTo(BigDecimal.ZERO) * lastDiff.compareTo(BigDecimal.ZERO) > 0) {
       trendMaMonitor.setTrendDays(trendMaMonitor.getTrendDays() + 1);
       BigDecimal absDiff = diff.abs();
       BigDecimal absLastDiff = lastDiff.abs();
       if (absLastDiff.compareTo(absDiff) > 0) {
         int returnDays =
             absDiff.divide(absLastDiff.subtract(absDiff), 0, RoundingMode.UP).intValue();
         trendMaMonitor.setReturnDays(returnDays);
       } else {
         trendMaMonitor.setReturnDays(null);
       }
     } else if (diff.compareTo(BigDecimal.ZERO) * lastDiff.compareTo(BigDecimal.ZERO) < 0) {
       trendMaMonitor.setTrendDays(1);
       trendMaMonitor.setReturnDays(0);
     }
   }
 }
 /** Set initial value to display */
 public NumberPickerBuilder setCurrentNumber(BigDecimal number) {
   if (number != null) {
     if (number.signum() >= 0) {
       this.currentSignValue = NumberPicker.SIGN_POSITIVE;
     } else {
       this.currentSignValue = NumberPicker.SIGN_NEGATIVE;
       number = number.abs();
     }
     BigDecimal[] numberInput = number.divideAndRemainder(BigDecimal.ONE);
     this.currentNumberValue = numberInput[0].intValue();
     this.currentDecimalValue = numberInput[1].doubleValue();
   }
   return this;
 }
예제 #12
0
  public String format(BigDecimal d) {

    if (d == null) d = BigDecimal.ZERO;

    if (this.isBlankWhenZero() && d.compareTo(BigDecimal.ZERO) == 0) return blankWhenZero("0");

    if (sym != null) {
      if (getNumberFormat() != null)
        return suppressLeadingZeros(
            addSign(
                getNumberFormat()
                    .format(
                        d.abs()
                            .setScale(
                                getNumberFormat().getMaximumFractionDigits(), RoundingMode.DOWN)
                            .multiply(BigDecimal.TEN.pow(scale))),
                (d.signum() < 0)));
      else if (sym.type == Constants.STRING) {
        return format(d.abs().toPlainString());
      }
    }

    return d.toString();
  }
예제 #13
0
파일: Dur.java 프로젝트: james-jw/basex
 /**
  * Adds the time to the specified token builder.
  *
  * @param tb token builder
  */
 final void time(final TokenBuilder tb) {
   if (sec.remainder(DAYSECONDS).signum() == 0) return;
   tb.add('T');
   final long h = hou();
   if (h != 0) {
     tb.addLong(Math.abs(h));
     tb.add('H');
   }
   final long m = min();
   if (m != 0) {
     tb.addLong(Math.abs(m));
     tb.add('M');
   }
   final BigDecimal sc = sec();
   if (sc.signum() == 0) return;
   tb.add(Token.chopNumber(Token.token(sc.abs().toPlainString()))).add('S');
 }
예제 #14
0
파일: Portfolio.java 프로젝트: c0debrain/pm
 @Transient
 public BigDecimal getTotalOutAmountEver(
     Date currentStartDate, Date currentEndDate, Currency targetCurrency) {
   BigDecimal ret = BigDecimal.ZERO;
   for (TransactionElement te : headTransactionsTo(currentStartDate, currentEndDate)) {
     if (te.transactionType().equals(TransactionType.AOUT)) {
       BigDecimal convertedPrice =
           getCurrencyConverter()
               .convert(te.getCurrency(), targetCurrency, te.getPrice(), te.getDate());
       ret =
           ret.add(
               convertedPrice.multiply(te.getQuantity()).setScale(10, BigDecimal.ROUND_HALF_EVEN));
     }
     ;
   }
   return ret.abs();
 }
 public static String castToString(BigDecimal val) {
   int sign = val.signum();
   val = val.abs();
   String s = val.unscaledValue().toString();
   while (s.length() <= val.scale()) s = "0" + s;
   while (s.length() < -val.scale()) s = s + "0";
   if (val.scale() > 0) {
     s =
         s.substring(0, s.length() - val.scale())
             + "."
             + s.substring(s.length() - val.scale(), s.length());
     while (s.endsWith("0")) s = s.substring(0, s.length() - 1);
     if (s.endsWith(".")) s = s.substring(0, s.length() - 1);
   }
   if (sign < 0) s = "-" + s;
   return s;
 }
예제 #16
0
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
    assert actionBar != null;
    actionBar.setTitle(R.string.title_split_editor);
    setHasOptionsMenu(true);

    mCalculatorKeyboard =
        new CalculatorKeyboard(getActivity(), mKeyboardView, R.xml.calculator_keyboard);
    mSplitItemViewList = new ArrayList<>();

    // we are editing splits for a new transaction.
    // But the user may have already created some splits before. Let's check
    List<String> splitStrings = getArguments().getStringArrayList(UxArgument.SPLIT_LIST);
    List<Split> splitList = new ArrayList<>();
    if (splitStrings != null) {
      for (String splitString : splitStrings) {
        splitList.add(Split.parseSplit(splitString));
      }
    }

    initArgs();
    if (!splitList.isEmpty()) {
      // aha! there are some splits. Let's load those instead
      loadSplitViews(splitList);
      mImbalanceWatcher.afterTextChanged(null);
    } else {
      final String currencyCode = mAccountsDbAdapter.getAccountCurrencyCode(mAccountUID);
      Split split =
          new Split(new Money(mBaseAmount.abs(), Commodity.getInstance(currencyCode)), mAccountUID);
      AccountType accountType = mAccountsDbAdapter.getAccountType(mAccountUID);
      TransactionType transactionType =
          Transaction.getTypeForBalance(accountType, mBaseAmount.signum() < 0);
      split.setType(transactionType);
      View view = addSplitView(split);
      view.findViewById(R.id.input_accounts_spinner).setEnabled(false);
      view.findViewById(R.id.btn_remove_split).setVisibility(View.GONE);
      TransactionsActivity.displayBalance(
          mImbalanceTextView, new Money(mBaseAmount.negate(), mCommodity));
    }
  }
  private BigDecimal[] relativeCloses(
      Quotations stockQuotations,
      MInteger startDateQuotationIndex,
      MInteger endDateQuotationIndex,
      BigDecimal unitCost) {

    ArrayList<BigDecimal> retA = new ArrayList<BigDecimal>();

    for (int i = startDateQuotationIndex.value; i <= endDateQuotationIndex.value; i++) {
      BigDecimal value = BigDecimal.ZERO;
      if (unitCost.compareTo(BigDecimal.ZERO) != 0) {
        BigDecimal close = stockQuotations.get(i).getClose();
        value = (close.subtract(unitCost).divide(unitCost.abs(), 10, BigDecimal.ROUND_HALF_EVEN));
      }
      retA.add(value);
    }

    return retA.toArray(new BigDecimal[0]);
  }
예제 #18
0
파일: Portfolio.java 프로젝트: c0debrain/pm
 @Override
 public BigDecimal getCashOutFor(
     PortfolioShare portfolioShare,
     Date currentStartDate,
     Date currentEndDate,
     Currency targetCurrency) {
   BigDecimal ret = BigDecimal.ZERO;
   for (TransactionElement te : headTransactionsTo(currentStartDate, currentEndDate)) {
     if (te.transactionType().equals(TransactionType.AOUT)
         && te.getStock().equals(portfolioShare.getStock())) {
       BigDecimal convertedPrice =
           getCurrencyConverter()
               .convert(te.getCurrency(), targetCurrency, te.getPrice(), te.getDate());
       ret =
           ret.add(
               convertedPrice.multiply(te.getQuantity()).setScale(10, BigDecimal.ROUND_HALF_EVEN));
     }
   }
   return ret.abs();
 }
예제 #19
0
  /**
   * Extracts the input from the views and builds {@link org.gnucash.android.model.Split}s to
   * correspond to the input.
   *
   * @return List of {@link org.gnucash.android.model.Split}s represented in the view
   */
  private List<Split> extractSplitsFromView() {
    List<Split> splitList = new ArrayList<>();
    for (View splitView : mSplitItemViewList) {
      SplitViewHolder viewHolder = (SplitViewHolder) splitView.getTag();
      if (viewHolder.splitAmountEditText.getValue() == null) continue;

      BigDecimal amountBigDecimal = viewHolder.splitAmountEditText.getValue();

      String currencyCode = mAccountsDbAdapter.getCurrencyCode(mAccountUID);
      Money valueAmount = new Money(amountBigDecimal.abs(), Commodity.getInstance(currencyCode));

      String accountUID = mAccountsDbAdapter.getUID(viewHolder.accountsSpinner.getSelectedItemId());
      Split split = new Split(valueAmount, accountUID);
      split.setMemo(viewHolder.splitMemoEditText.getText().toString());
      split.setType(viewHolder.splitTypeSwitch.getTransactionType());
      split.setUID(viewHolder.splitUidTextView.getText().toString().trim());
      if (viewHolder.quantity != null) split.setQuantity(viewHolder.quantity.absolute());
      splitList.add(split);
    }
    return splitList;
  }
예제 #20
0
파일: Support.java 프로젝트: floatin/Weave
  /**
   * Normalize a BigDecimal value so that it fits within the available precision.
   *
   * @param value The decimal value to normalize.
   * @param maxPrecision The decimal precision supported by the server (assumed to be a value of
   *     either 28 or 38).
   * @return The possibly normalized decimal value as a <code>BigDecimal</code>.
   * @throws SQLException If the number is too big.
   */
  static BigDecimal normalizeBigDecimal(BigDecimal value, int maxPrecision) throws SQLException {

    if (value == null) {
      return null;
    }

    if (value.scale() < 0) {
      // Java 1.5 BigDecimal allows negative scales.
      // jTDS cannot send these so re-scale.
      value = value.setScale(0);
    }

    if (value.scale() > maxPrecision) {
      // This is an optimization to quickly adjust the scale of a
      // very precise BD value. For example
      // BigDecimal((double)1.0/3.0) yields a BD 54 digits long!
      value = value.setScale(maxPrecision, BigDecimal.ROUND_HALF_UP);
    }

    BigInteger max = (maxPrecision == TdsData.DEFAULT_PRECISION_28) ? MAX_VALUE_28 : MAX_VALUE_38;

    while (value.abs().unscaledValue().compareTo(max) > 0) {
      // OK we need to reduce the scale if possible to preserve
      // the integer part of the number and still fit within the
      // available precision.
      int scale = value.scale() - 1;

      if (scale < 0) {
        // Can't do it number just too big
        throw new SQLException(
            Messages.get("error.normalize.numtoobig", String.valueOf(maxPrecision)), "22000");
      }

      value = value.setScale(scale, BigDecimal.ROUND_HALF_UP);
    }

    return value;
  }
예제 #21
0
  /**
   * Calculate the number of digits to the left of the decimal point of the passed in value.
   *
   * @param decimalValue Value to get whole digits from, never null.
   * @return number of whole digits.
   */
  private static int getWholeDigits(BigDecimal decimalValue) {
    /** if ONE > abs(value) then the number of whole digits is 0 */
    decimalValue = decimalValue.abs();
    if (ONE.compareTo(decimalValue) == 1) {
      return 0;
    }

    if (bdPrecision != null) {
      // use reflection so we can still compile using JDK1.4
      // if we are prepared to require 1.5 to compile then this can be a
      // direct call
      try {
        // precision is the number of digits in the unscaled value,
        // subtracting the scale (positive or negative) will give the
        // number of whole digits.
        int precision = ((Integer) bdPrecision.invoke(decimalValue, null)).intValue();
        return precision - decimalValue.scale();
      } catch (IllegalAccessException e) {
        // can't happen based on the JDK spec
        throw new IllegalAccessError("precision");
      } catch (InvocationTargetException e) {
        Throwable t = e.getTargetException();
        if (t instanceof RuntimeException) {
          throw (RuntimeException) t;
        } else if (t instanceof Error) {
          throw (Error) t;
        } else {
          // can't happen
          throw new IncompatibleClassChangeError("precision");
        }
      }
    }

    String s = decimalValue.toString();
    return (decimalValue.scale() == 0) ? s.length() : s.indexOf('.');
  }
예제 #22
0
  /**
   * @param indVar
   * @return
   * @throws InvalidOperatorException
   * @throws OperatorDomainException
   */
  public BigDecimal eval(BigDecimal indVar)
      throws InvalidOperatorException, OperatorDomainException {
    if (OPCODE == Operand.INDEP_VAR) return indVar.round(CalcConst.MC);
    if (OPCODE == Operand.CONSTANT) return ((BigDecimal) OPERAND1).round(CalcConst.MC);

    if (TWO_OP) {
      BigDecimal op1, op2;
      op1 = op2 = null;
      if (OPERAND1 instanceof Operation) {
        op1 = ((Operation) OPERAND1).eval(indVar);
      } else if (OPERAND1 instanceof BigDecimal) {
        op1 = ((BigDecimal) OPERAND1);
      }
      if (OPERAND2 instanceof Operation) {
        op2 = ((Operation) OPERAND2).eval(indVar);
      } else if (OPERAND2 instanceof BigDecimal) {
        op2 = ((BigDecimal) OPERAND2);
      }

      try {
        switch (OPCODE) {
          case PLUS:
            return op1.add(op2, CalcConst.MC);
          case MINUS:
            return op1.subtract(op2, CalcConst.MC);
          case MULT:
            return op1.multiply(op2, CalcConst.MC);
          case DIV:
            return op1.divide(op2, CalcConst.MC);
          case POW:
            return new BigDecimal(Math.pow(op1.doubleValue(), op2.doubleValue()), CalcConst.MC);
          default:
            throw new InvalidOperatorException("Invalid Opertor for 2-variable operation");
        }
      } catch (ArithmeticException eA) {
        throw new OperatorDomainException("Input is outside operator's domain");
      }
    } else {
      BigDecimal op;
      op = null;
      if (OPERAND1 instanceof Operation) {
        op = ((Operation) OPERAND1).eval(indVar);
      } else if (OPERAND1 instanceof BigDecimal) {
        op = ((BigDecimal) OPERAND1);
      }

      try {
        switch (OPCODE) {
          case SQRT:
            return new BigDecimal(Math.sqrt(op.doubleValue()), CalcConst.MC);
          case CBRT:
            return new BigDecimal(Math.cbrt(op.doubleValue()), CalcConst.MC);
          case LOG:
            return new BigDecimal(Math.log10(op.doubleValue()), CalcConst.MC);
          case NLOG:
            return new BigDecimal(Math.log(op.doubleValue()), CalcConst.MC);
          case SIN:
            return new BigDecimal(Math.sin(op.doubleValue()), CalcConst.MC);
          case COS:
            return new BigDecimal(Math.cos(op.doubleValue()), CalcConst.MC);
          case TAN:
            return new BigDecimal(Math.tan(op.doubleValue()), CalcConst.MC);
          case CSC:
            return new BigDecimal(1.0 / Math.sin(op.doubleValue()), CalcConst.MC);
          case SEC:
            return new BigDecimal(1.0 / Math.cos(op.doubleValue()), CalcConst.MC);
          case COT:
            return new BigDecimal(1.0 / Math.tan(op.doubleValue()), CalcConst.MC);
          case ARCSIN:
            return new BigDecimal(Math.asin(op.doubleValue()), CalcConst.MC);
          case ARCCOS:
            return new BigDecimal(Math.acos(op.doubleValue()), CalcConst.MC);
          case ARCTAN:
            return new BigDecimal(Math.atan(op.doubleValue()), CalcConst.MC);
          case ARCCSC:
            return new BigDecimal(Math.asin(1.0 / op.doubleValue()), CalcConst.MC);
          case ARCSEC:
            return new BigDecimal(Math.acos(1.0 / op.doubleValue()), CalcConst.MC);
          case ARCCOT:
            return new BigDecimal(Math.atan(1.0 / op.doubleValue()), CalcConst.MC);
          case NEG:
            return op.negate(CalcConst.MC);
          case ABS:
            return op.abs(CalcConst.MC);
          default:
            throw new InvalidOperatorException("Invalid Operator for 1-variable operation");
        }
      } catch (NumberFormatException eNF) {
        throw new OperatorDomainException("Input is outside operator's domain");
      } catch (ArithmeticException eA) {
        throw new OperatorDomainException("Input is outside operator's domain");
      }
    }
  }
 @Override
 protected BigDecimal abs(BigDecimal x) {
   return x.abs();
 }
  /**
   * Computes the color that corresponds to the LightDefinition entry for which the limits match the
   * value read from field.
   *
   * @return the computed color.
   */
  private Color computeColor() {
    if (field == null) {
      return defaultColor;
    }

    final Object o = getDataRow().get(field);
    if (o instanceof Number == false) {
      return defaultColor;
    }

    final Number n = (Number) o;
    final Number value;
    if (useAbsoluteValue) {
      if (n instanceof BigDecimal) {
        final BigDecimal td = (BigDecimal) n;
        value = td.abs();
      } else {
        final BigDecimal td = new BigDecimal(n.toString());
        value = td.abs();
      }
    } else {
      value = n;
    }

    if (lightDefArray == null) {
      lightDefArray = limits.toArray(new LightDefinition[limits.size()]);
      Arrays.sort(lightDefArray);
    }

    if (useOppositeLogic) {
      // Inverse logic. The first interval ranging from '-INF' to the first limit will use the
      // first color. If the value is in the range 'limit[i]' and 'limit[i+1]', the color[i+1]
      // will be used. If the value is greater than the last limit, the default color is used.

      if (limits.isEmpty()) {
        return defaultColor;
      }

      Color returnColor = defaultColor;
      for (int i = lightDefArray.length - 1; i >= 0; i--) {
        final LightDefinition definition = lightDefArray[i];
        if (definition == null) {
          continue;
        }
        final Number limit = definition.getLimit();
        if (limit == null) {
          continue;
        }
        if (value.doubleValue() < limit.doubleValue()) {
          returnColor = definition.getColor();
        }
      }
      if (returnColor == null) {
        return defaultColor;
      }
      return returnColor;
    } else {
      // Standard logic. The first interval from '-INF' to the first limit uses the default color.
      // from there, the color for the first limit that is greater than the given value is used.
      // For the interval ranging from the last limit to '+INF', the last color is used.
      // If there are no limits defined, the default color is always used.

      Color returnColor = defaultColor;
      for (int i = 0; i < lightDefArray.length; i++) {
        final LightDefinition definition = lightDefArray[i];
        if (definition == null) {
          continue;
        }
        final Number limit = definition.getLimit();
        if (limit == null) {
          continue;
        }
        if (value.doubleValue() >= limit.doubleValue()) {
          returnColor = definition.getColor();
        }
      }
      if (returnColor == null) {
        return defaultColor;
      }
      return returnColor;
    }
  }
예제 #25
0
파일: Amount.java 프로젝트: kob-aha/gradle
 public Amount<Q> abs() {
   if (value.compareTo(BigDecimal.ZERO) >= 0) {
     return this;
   }
   return new Amount<Q>(value.abs(), units);
 }
예제 #26
0
    @Override
    protected Rotation<BigDecimal>[] rotations(
        final PhysicalStore<BigDecimal> aStore,
        final int aLowInd,
        final int aHighInd,
        final Rotation<BigDecimal>[] retVal) {

      final BigDecimal a00 = aStore.get(aLowInd, aLowInd);
      final BigDecimal a01 = aStore.get(aLowInd, aHighInd);
      final BigDecimal a10 = aStore.get(aHighInd, aLowInd);
      final BigDecimal a11 = aStore.get(aHighInd, aHighInd);

      final BigDecimal x = a00.add(a11);
      final BigDecimal y = a10.subtract(a01);

      BigDecimal t; // tan, cot or something temporary

      // Symmetrise - Givens
      final BigDecimal cg; // cos Givens
      final BigDecimal sg; // sin Givens

      if (y.signum() == 0) {
        cg = BigFunction.SIGNUM.invoke(x);
        sg = BigMath.ZERO;
      } else if (x.signum() == 0) {
        sg = BigFunction.SIGNUM.invoke(y);
        cg = BigMath.ZERO;
      } else if (y.abs().compareTo(x.abs()) == 1) {
        t = BigFunction.DIVIDE.invoke(x, y); // cot
        sg =
            BigFunction.DIVIDE.invoke(BigFunction.SIGNUM.invoke(y), BigFunction.SQRT1PX2.invoke(t));
        cg = sg.multiply(t);
      } else {
        t = BigFunction.DIVIDE.invoke(y, x); // tan
        cg =
            BigFunction.DIVIDE.invoke(BigFunction.SIGNUM.invoke(x), BigFunction.SQRT1PX2.invoke(t));
        sg = cg.multiply(t);
      }

      final BigDecimal b00 = cg.multiply(a00).add(sg.multiply(a10));
      final BigDecimal b11 = cg.multiply(a11).subtract(sg.multiply(a01));
      final BigDecimal b2 =
          cg.multiply(a01.add(a10)).add(sg.multiply(a11.subtract(a00))); // b01 + b10

      t = BigFunction.DIVIDE.invoke(b11.subtract(b00), b2);
      t =
          BigFunction.DIVIDE.invoke(
              BigFunction.SIGNUM.invoke(t), BigFunction.SQRT1PX2.invoke(t).add(t.abs()));

      // Annihilate - Jacobi
      final BigDecimal cj =
          BigFunction.DIVIDE.invoke(BigMath.ONE, BigFunction.SQRT1PX2.invoke(t)); // Cos Jacobi
      final BigDecimal sj = cj.multiply(t); // Sin Jacobi

      retVal[1] = new Rotation.Big(aLowInd, aHighInd, cj, sj); // Jacobi
      retVal[0] =
          new Rotation.Big(
              aLowInd,
              aHighInd,
              cj.multiply(cg).add(sj.multiply(sg)),
              cj.multiply(sg).subtract(sj.multiply(cg))); // Givens - Jacobi

      return retVal;
    }
예제 #27
0
  /**
   * * 插入FN311 OP_SYS=财务系统 OP_MODEL=初始数据 OP_BUTTON=2 OP_IP=操作员ip OP_TIME=系统时间 OPERATOR=操作员 插入FN201:
   * BOOK_ID=所属账套 SUBJECT_CODE=科目代码 SUMMAY=1 DEBIT=累计借方 CREDIT=累计贷方 MAKEBILL=操作员 OFFICE=所选办事处
   *
   * @param datainitializeDTO 张列
   * @param securityInfo
   * @throws Exception
   */
  public void insertSummaryOffice(List list, SecurityInfo securityInfo) throws Exception {
    try {
      if (list.size() != 0) {
        DatainitializeDTO datainitializeDTO1 = (DatainitializeDTO) list.get(0);
        // 插入FN311
        FnOperateLog fnOperateLog = new FnOperateLog();
        fnOperateLog.setOpSys(BusiLogConst.OP_SYSTEM_TYPE_FINANCE + "");
        fnOperateLog.setOpModel(BusiLogConst.FN_OP_BOOKMNG_DATAINITIALIZE + "");
        fnOperateLog.setOpButton("1");
        fnOperateLog.setOpIp(securityInfo.getUserIp());
        fnOperateLog.setOpTime(new Date());
        fnOperateLog.setOperator(securityInfo.getUserName());
        fnOperateLog.setBookId(datainitializeDTO1.getBookId());
        fnOperateLogDAO.insert(fnOperateLog);
        Iterator it = list.iterator();
        while (it.hasNext()) {
          DatainitializeDTO datainitializeDTO = (DatainitializeDTO) it.next();
          //          if(datainitializeDTO.getDebit().equals("0") &&
          // datainitializeDTO.getCredit().equals("0")){
          //            continue;
          //          }else{
          // 插入 FN201
          AccountantCredence accountantCredence = new AccountantCredence();
          accountantCredence.setBookId(datainitializeDTO.getBookId());
          accountantCredence.setSubjectCode(datainitializeDTO.getSubjectCode());
          accountantCredence.setSummay(bookParameterDAO.getSummay(datainitializeDTO.getBookId()));

          accountantCredence.setDebit(new BigDecimal(datainitializeDTO.getDebit()));
          accountantCredence.setCredit(new BigDecimal(datainitializeDTO.getCredit()));

          accountantCredence.setMakebill(securityInfo.getUserName());
          accountantCredence.setOffice(datainitializeDTO.getOfficeName());
          accountantCredence.setCredenceSt("2");
          // 年
          String date1 = bookDAO.getUseYearmonth(datainitializeDTO.getBookId()) + "01";
          DateFormat df = new SimpleDateFormat("yyyyMMdd");
          String year = "";
          try {
            Date d1 = df.parse(date1);
            // System.out.println("d1=="+df.format(d1));
            Calendar g = Calendar.getInstance();
            g.setTime(d1);
            g.add(Calendar.DATE, -1);
            Date d2 = g.getTime();
            // System.out.println("d2======="+df.format(d2));
            year = df.format(d2);
          } catch (ParseException exx) {
            exx.printStackTrace();
          }
          accountantCredence.setCredenceDate(year);
          accountantCredence.setSettDate(year);
          // 如果是(损益类科目)直接把FN201中的(损益结转字段置为2)
          if (subjectDAO
              .getSortcodeByCode_WL(datainitializeDTO.getSubjectCode(), securityInfo)
              .equals("4")) {
            accountantCredence.setIncDecSt("2");
          }
          if (subjectDAO
              .getProperyByCode_WL(datainitializeDTO.getSubjectCode(), securityInfo)
              .equals("0")) {
            // 如果是(银行属性的科目)直接把(银行账结转状态置为2)
            accountantCredence.setBankAccSt("2");
          }
          if (subjectDAO
              .getProperyByCode_WL(datainitializeDTO.getSubjectCode(), securityInfo)
              .equals("1")) {
            // 如果是(现金属性的科目)直接把(现金账结转状态置为2)
            accountantCredence.setCashAccSt("2");
          }
          accountantCredenceDAO.insert(accountantCredence);
          //          }
        }
        Iterator it1 = list.iterator();
        while (it1.hasNext()) {
          DatainitializeDTO datainitializeDTO11 = (DatainitializeDTO) it1.next();
          //          if(datainitializeDTO11.getYesterdayRemainingSum().equals("0") ||
          // datainitializeDTO11.getBalaceDirection().equals("2")){
          //            continue;
          //          }
          AccountantCredence accountantCredence = new AccountantCredence();
          accountantCredence.setBookId(datainitializeDTO11.getBookId());
          accountantCredence.setSubjectCode(datainitializeDTO11.getSubjectCode());
          accountantCredence.setSummay(
              bookParameterDAO.getSummay4(datainitializeDTO11.getBookId()));
          if (datainitializeDTO11.getBalaceDirection().equals("0")) {
            BigDecimal temp =
                new BigDecimal(datainitializeDTO11.getYesterdayRemainingSum())
                    .subtract(new BigDecimal(datainitializeDTO11.getDebit()))
                    .add(new BigDecimal(datainitializeDTO11.getCredit()))
                    .subtract(new BigDecimal(datainitializeDTO11.getYesterdayDebit()))
                    .add(new BigDecimal(datainitializeDTO11.getYesterdayCredit()));
            accountantCredence.setDebit(temp);
            accountantCredence.setCredit(new BigDecimal("0.00"));
          }
          if (datainitializeDTO11.getBalaceDirection().equals("1")) {
            BigDecimal temp =
                new BigDecimal(datainitializeDTO11.getYesterdayRemainingSum())
                    .subtract(new BigDecimal(datainitializeDTO11.getCredit()))
                    .add(new BigDecimal(datainitializeDTO11.getDebit()))
                    .subtract(new BigDecimal(datainitializeDTO11.getYesterdayCredit()))
                    .add(new BigDecimal(datainitializeDTO11.getYesterdayDebit()));
            accountantCredence.setDebit(new BigDecimal("0.00"));
            accountantCredence.setCredit(temp);
          }
          if (datainitializeDTO11.getBalaceDirection().equals("2")) {
            {
              BigDecimal temp_yeaterdayDebit =
                  new BigDecimal(datainitializeDTO11.getYesterdayDebit());
              BigDecimal temp_debit = new BigDecimal(datainitializeDTO11.getDebit());
              BigDecimal temp_yeaterdayCredit =
                  new BigDecimal(datainitializeDTO11.getYesterdayCredit());
              BigDecimal temp_credit = new BigDecimal(datainitializeDTO11.getCredit());
              //            BigDecimal temp =
              // temp_yeaterdayDebit.add(temp_debit).subtract(temp_yeaterdayCredit).subtract(temp_credit);
              BigDecimal temp =
                  temp_yeaterdayCredit
                      .add(temp_credit)
                      .subtract(temp_yeaterdayDebit)
                      .subtract(temp_debit);
              if (temp.compareTo(new BigDecimal(0)) > 0) {
                accountantCredence.setDebit(temp.abs());
                accountantCredence.setCredit(new BigDecimal("0.00"));
              }
              if (temp.compareTo(new BigDecimal(0)) < 0) {
                accountantCredence.setDebit(new BigDecimal("0.00"));
                accountantCredence.setCredit(temp.abs());
              }
              if (temp.compareTo(new BigDecimal(0)) == 0) {
                //                if(temp_yeaterdayDebit.compareTo(new BigDecimal(0))==0 &&
                // temp_debit.compareTo(new BigDecimal(0))==0 && temp_yeaterdayCredit.compareTo(new
                // BigDecimal(0))==0 && temp_credit.compareTo(new BigDecimal(0))==0 ){
                //                  continue;
                //                }else{
                accountantCredence.setDebit(new BigDecimal("0.00"));
                accountantCredence.setCredit(new BigDecimal("0.00"));
                //                }
              }
            }
          }

          accountantCredence.setMakebill(securityInfo.getUserName());
          accountantCredence.setOffice(datainitializeDTO11.getOfficeName());
          accountantCredence.setCredenceSt("2");

          // 年
          String year =
              (Integer.parseInt(
                          bookDAO.getUseYearmonth(datainitializeDTO11.getBookId()).substring(0, 4))
                      - 2)
                  + "1231";
          accountantCredence.setCredenceDate(year);
          accountantCredence.setSettDate(year);

          // 如果是(损益类科目)直接把FN201中的(损益结转字段置为2)
          if (subjectDAO
              .getSortcodeByCode_WL(datainitializeDTO11.getSubjectCode(), securityInfo)
              .equals("4")) {
            accountantCredence.setIncDecSt("2");
          }
          if (subjectDAO
              .getProperyByCode_WL(datainitializeDTO11.getSubjectCode(), securityInfo)
              .equals("0")) {
            // 如果是(银行属性的科目)直接把(银行账结转状态置为2)
            accountantCredence.setBankAccSt("2");
          }
          if (subjectDAO
              .getProperyByCode_WL(datainitializeDTO11.getSubjectCode(), securityInfo)
              .equals("1")) {
            // 如果是(现金属性的科目)直接把(现金账结转状态置为2)
            accountantCredence.setCashAccSt("2");
          }
          accountantCredenceDAO.insert(accountantCredence);
        }
        Iterator it2 = list.iterator();
        while (it2.hasNext()) {
          DatainitializeDTO datainitializeDTO2 = (DatainitializeDTO) it2.next();
          //          if(datainitializeDTO2.getYesterdayDebit().equals("0") &&
          // datainitializeDTO2.getYesterdayCredit().equals("0")){
          //            continue;
          //          }
          AccountantCredence accountantCredence = new AccountantCredence();
          accountantCredence.setBookId(datainitializeDTO2.getBookId());
          accountantCredence.setSubjectCode(datainitializeDTO2.getSubjectCode());
          accountantCredence.setSummay(bookParameterDAO.getSummay5(datainitializeDTO2.getBookId()));

          accountantCredence.setDebit(new BigDecimal(datainitializeDTO2.getYesterdayDebit()));
          accountantCredence.setCredit(new BigDecimal(datainitializeDTO2.getYesterdayCredit()));

          accountantCredence.setMakebill(securityInfo.getUserName());
          accountantCredence.setOffice(datainitializeDTO2.getOfficeName());
          accountantCredence.setCredenceSt("2");

          // 年
          String year =
              (Integer.parseInt(
                          bookDAO.getUseYearmonth(datainitializeDTO2.getBookId()).substring(0, 4))
                      - 1)
                  + "1231";
          accountantCredence.setCredenceDate(year);
          accountantCredence.setSettDate(year);

          // 如果是(损益类科目)直接把FN201中的(损益结转字段置为2)
          if (subjectDAO
              .getSortcodeByCode_WL(datainitializeDTO2.getSubjectCode(), securityInfo)
              .equals("4")) {
            accountantCredence.setIncDecSt("2");
          }
          if (subjectDAO
              .getProperyByCode_WL(datainitializeDTO2.getSubjectCode(), securityInfo)
              .equals("0")) {
            // 如果是(银行属性的科目)直接把(银行账结转状态置为2)
            accountantCredence.setBankAccSt("2");
          }
          if (subjectDAO
              .getProperyByCode_WL(datainitializeDTO2.getSubjectCode(), securityInfo)
              .equals("1")) {
            // 如果是(现金属性的科目)直接把(现金账结转状态置为2)
            accountantCredence.setCashAccSt("2");
          }
          accountantCredenceDAO.insert(accountantCredence);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #28
0
  /** Handle string insertion. */
  public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
    // Store source data

    int sourceLength = getLength();
    String sourceText = getText(0, sourceLength);
    StringBuffer strBuffer = new StringBuffer(sourceText);

    // Check if old value is zero

    if (offs == 0 && sourceLength > 0 && str.length() > 0) {
      long oldValue;

      try {
        oldValue = myFormat.parse(strBuffer.toString()).longValue();

        if (oldValue == 0) {
          strBuffer.deleteCharAt(0);
        }
      } catch (Exception e) {
      }
    }

    // Now add new string

    strBuffer.insert(offs, str);

    BigDecimal value;

    try {
      value = new BigDecimal(myFormat.parse(strBuffer.toString()).doubleValue());
    } catch (Exception e) {
      if (sourceLength > 0) {
        if (sourceText.startsWith(",")) {
          sourceText = "0" + sourceText;
        }

        value = new BigDecimal(getRealString(sourceText));
      } else {
        value = new BigDecimal(0.0);
      }
    }

    // Set the new value

    if (textField == null) {
      return;
    }

    textField.setValue(new Money(value, textField.getValue().getCurrency()), false);

    super.remove(0, sourceLength);
    super.insertString(0, myFormat.format(value.doubleValue()), a);

    // Set caret to correct caret position

    if (!"".equals(sourceText)) // <=> initilized
    {
      int lengthDiff = getLength() - sourceLength;
      int caretPos = lengthDiff + offs;
      int caretDiff = sourceLength - offs;

      // Adjust for columns after centSperator (currently Diff < 3)

      if ((caretDiff > 0 && caretDiff < 3) || (value.abs().longValue() < 10 && caretPos == 0)) {
        caretPos += 1;
      }

      if (caretPos < 0) {
        caretPos = 0;
      }

      textField.setCaretPosition(caretPos);
    } else {
      textField.setCaretPosition(1);
    }
  }
예제 #29
0
  private String formatDecimal(String start, SchemaType sType) {
    BigDecimal result = new BigDecimal(start);
    XmlDecimal xmlD;
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE);
    BigDecimal min = xmlD != null ? xmlD.getBigDecimalValue() : null;
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE);
    BigDecimal max = xmlD != null ? xmlD.getBigDecimalValue() : null;
    boolean minInclusive = true, maxInclusive = true;
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE);
    if (xmlD != null) {
      BigDecimal minExcl = xmlD.getBigDecimalValue();
      if (min == null || min.compareTo(minExcl) < 0) {
        min = minExcl;
        minInclusive = false;
      }
    }
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE);
    if (xmlD != null) {
      BigDecimal maxExcl = xmlD.getBigDecimalValue();
      if (max == null || max.compareTo(maxExcl) > 0) {
        max = maxExcl;
        maxInclusive = false;
      }
    }
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_TOTAL_DIGITS);
    int totalDigits = -1;
    if (xmlD != null) {
      totalDigits = xmlD.getBigDecimalValue().intValue();

      StringBuffer sb = new StringBuffer(totalDigits);
      for (int i = 0; i < totalDigits; i++) sb.append('9');
      BigDecimal digitsLimit = new BigDecimal(sb.toString());
      if (max != null && max.compareTo(digitsLimit) > 0) {
        max = digitsLimit;
        maxInclusive = true;
      }
      digitsLimit = digitsLimit.negate();
      if (min != null && min.compareTo(digitsLimit) < 0) {
        min = digitsLimit;
        minInclusive = true;
      }
    }

    int sigMin = min == null ? 1 : result.compareTo(min);
    int sigMax = max == null ? -1 : result.compareTo(max);
    boolean minOk = sigMin > 0 || sigMin == 0 && minInclusive;
    boolean maxOk = sigMax < 0 || sigMax == 0 && maxInclusive;

    // Compute the minimum increment
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_FRACTION_DIGITS);
    int fractionDigits = -1;
    BigDecimal increment;
    if (xmlD == null) increment = new BigDecimal(1);
    else {
      fractionDigits = xmlD.getBigDecimalValue().intValue();
      if (fractionDigits > 0) {
        StringBuffer sb = new StringBuffer("0.");
        for (int i = 1; i < fractionDigits; i++) sb.append('0');
        sb.append('1');
        increment = new BigDecimal(sb.toString());
      } else increment = new BigDecimal(1);
    }

    if (minOk && maxOk) {
      // OK
    } else if (minOk && !maxOk) {
      // TOO BIG
      if (maxInclusive) result = max;
      else result = max.subtract(increment);
    } else if (!minOk && maxOk) {
      // TOO SMALL
      if (minInclusive) result = min;
      else result = min.add(increment);
    } else {
      // MIN > MAX!!
    }

    // We have the number
    // Adjust the scale according to the totalDigits and fractionDigits
    int digits = 0;
    BigDecimal ONE = new BigDecimal(BigInteger.ONE);
    for (BigDecimal n = result; n.abs().compareTo(ONE) >= 0; digits++) n = n.movePointLeft(1);

    if (fractionDigits > 0)
      if (totalDigits >= 0) result.setScale(Math.max(fractionDigits, totalDigits - digits));
      else result.setScale(fractionDigits);
    else if (fractionDigits == 0) result.setScale(0);

    return result.toString();
  }
예제 #30
0
 /**
  * Create actual Payment
  *
  * @param C_Invoice_ID invoice
  * @param C_BPartner_ID partner ignored when invoice exists
  * @param C_Currency_ID currency
  * @param StmtAmt statement amount
  * @param TrxAmt transaction amt
  * @param C_BP_BankAccount_ID bank account
  * @param DateTrx transaction date
  * @param DateAcct accounting date
  * @param Description description
  * @param AD_Org_ID org
  * @return payment
  */
 private MPayment createPayment(
     int C_Invoice_ID,
     int C_BPartner_ID,
     int C_Currency_ID,
     BigDecimal StmtAmt,
     BigDecimal TrxAmt,
     int C_BP_BankAccount_ID,
     Timestamp DateTrx,
     Timestamp DateAcct,
     String Description,
     int AD_Org_ID) {
   //	Trx Amount = Payment overwrites Statement Amount if defined
   BigDecimal PayAmt = TrxAmt;
   if (PayAmt == null || Env.ZERO.compareTo(PayAmt) == 0) PayAmt = StmtAmt;
   if (C_Invoice_ID == 0 && (PayAmt == null || Env.ZERO.compareTo(PayAmt) == 0))
     throw new IllegalStateException("@PayAmt@ = 0");
   if (PayAmt == null) PayAmt = Env.ZERO;
   //
   MPayment payment = new MPayment(getCtx(), 0, get_TrxName());
   payment.setAD_Org_ID(AD_Org_ID);
   payment.setC_BP_BankAccount_ID(C_BP_BankAccount_ID);
   payment.setTenderType(MPayment.TENDERTYPE_Check);
   if (DateTrx != null) payment.setDateTrx(DateTrx);
   else if (DateAcct != null) payment.setDateTrx(DateAcct);
   if (DateAcct != null) payment.setDateAcct(DateAcct);
   else payment.setDateAcct(payment.getDateTrx());
   payment.setDescription(Description);
   //
   if (C_Invoice_ID != 0) {
     MInvoice invoice = new MInvoice(getCtx(), C_Invoice_ID, null);
     payment.setC_DocType_ID(invoice.isSOTrx()); // 	Receipt
     payment.setC_Invoice_ID(invoice.getC_Invoice_ID());
     payment.setC_BPartner_ID(invoice.getC_BPartner_ID());
     if (PayAmt.signum() != 0) // 	explicit Amount
     {
       payment.setC_Currency_ID(C_Currency_ID);
       if (invoice.isSOTrx()) payment.setPayAmt(PayAmt);
       else //	payment is likely to be negative
       payment.setPayAmt(PayAmt.negate());
       payment.setOverUnderAmt(invoice.getGrandTotal(true).subtract(payment.getPayAmt()));
     } else // set Pay Amout from Invoice
     {
       payment.setC_Currency_ID(invoice.getC_Currency_ID());
       payment.setPayAmt(invoice.getGrandTotal(true));
     }
   } else if (C_BPartner_ID != 0) {
     payment.setC_BPartner_ID(C_BPartner_ID);
     payment.setC_Currency_ID(C_Currency_ID);
     if (PayAmt.signum() < 0) // 	Payment
     {
       payment.setPayAmt(PayAmt.abs());
       payment.setC_DocType_ID(false);
     } else //	Receipt
     {
       payment.setPayAmt(PayAmt);
       payment.setC_DocType_ID(true);
     }
   } else return null;
   payment.save();
   //
   payment.processIt(MPayment.DOCACTION_Complete);
   payment.save();
   return payment;
 } //	createPayment