Example usage for java.math BigDecimal subtract

List of usage examples for java.math BigDecimal subtract

Introduction

In this page you can find the example usage for java.math BigDecimal subtract.

Prototype

public BigDecimal subtract(BigDecimal subtrahend) 

Source Link

Document

Returns a BigDecimal whose value is (this - subtrahend) , and whose scale is max(this.scale(), subtrahend.scale()) .

Usage

From source file:org.techytax.business.zk.calendar.CalendarController.java

@Listen("onClick = #invoiceButton")
public void createInvoice() throws IOException {
    InputStream is = null;//  ww w  . ja va2 s .  c om
    try {

        Calendar cal = GregorianCalendar.getInstance();
        Date calendarDate = calendars.getCurrentDate();
        cal.setTime(calendarDate);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date endDate = cal.getTime();

        cal.set(Calendar.DAY_OF_MONTH, 1);
        Date beginDate = cal.getTime();
        List<CalendarEvent> eventList = calendarModel.get(beginDate, endDate, null);

        invoice = new Invoice();
        invoice.setUnitsOfWork(countUnitsOfWork(eventList));
        invoice.setMonth(DateHelper.getMaand(endDate));
        int jaar = cal.get(Calendar.YEAR);
        String factuurNummerString = Integer.toString(jaar);
        invoice.setYear(jaar);
        int maand = cal.get(Calendar.MONTH) + 1;
        if (maand < 10) {
            factuurNummerString += "0";
        }
        factuurNummerString += Integer.toString(maand);

        List<Cost> sentAndPaidInvoicesInPeriod = costDao
                .getInvoicesSentAndPaid(new FiscalPeriod(beginDate, new Date()));
        List<Cost> invoices = new ArrayList<>();

        for (Cost cost : sentAndPaidInvoicesInPeriod) {
            if (cost.getCostType().equals(INVOICE_SENT)) {
                if (cost.getDescription().contains(factuurNummerString)) {
                    invoices.add(cost);
                }
            }
        }

        int factuurAantal = invoices.size() + 1;
        String factuurAantalString = Integer.toString(factuurAantal);
        if (factuurAantal < 10) {
            factuurAantalString = "0" + factuurAantalString;
        }
        factuurNummerString += factuurAantalString;
        invoice.setInvoiceNumber(Integer.parseInt(factuurNummerString));
        invoice.setInvoiceDate(DateHelper.getInvoiceDateString(new Date()));
        invoice.setNofDays(44);
        invoice.setExpiryDate(DateHelper.getInvoiceDateString(DateHelper.getDateAfterDays(44)));

        Customer customer = selectedProject.getCustomer();
        sendInvoiceButton.setLabel(Labels.getLabel("send.invoice.to") + ": " + customer.getEmailInvoice());

        invoice.setConsumerAddress(customer.getFullAddress());
        invoice.setConsumerName(customer.getName());
        invoice.setVat(selectedProject.getVatType().getValueAsInteger(new Date()));
        invoice.setActivityDescription(selectedProject.getActivityDescription());
        invoice.setRate(selectedProject.getRate());

        BigDecimal netAmount = new BigDecimal(invoice.getUnitsOfWork() * invoice.getRate().floatValue());
        netAmount = AmountHelper.round(netAmount);

        invoice.setNetAmount(netAmount);
        invoice.setEmail(customer.getEmailInvoice());
        BigDecimal netAmountAfterDiscount = netAmount;
        if (StringUtils.isNotEmpty(discount.getValue())) {
            int discountPercentage = Integer.parseInt(discount.getValue());
            invoice.setDiscountPercentage(discountPercentage);
            BigDecimal discount = new BigDecimal(netAmount.doubleValue() * discountPercentage / 100.0d);
            invoice.setDiscount(discount);
            netAmountAfterDiscount = netAmount.subtract(discount);
            invoice.setNetAmountAfterDiscount(netAmountAfterDiscount);
        }
        BigDecimal btwBedrag = new BigDecimal(netAmountAfterDiscount.doubleValue() * invoice.getVat() / 100.0d);
        btwBedrag = AmountHelper.round(btwBedrag);
        BigDecimal totaalBedrag = netAmountAfterDiscount.add(btwBedrag);
        totaalBedrag = AmountHelper.round(totaalBedrag);
        invoice.setVatAmount(btwBedrag);
        invoice.setTotalAmount(totaalBedrag);
        invoice.setNetAmountAfterDiscount(netAmountAfterDiscount);
        PdfInvoiceHelper pdfInvoiceHelper = new PdfInvoiceHelper();
        invoiceBuf = pdfInvoiceHelper.createPdfInvoice(invoice, getUser());

        // prepare the AMedia for iframe
        final InputStream mediais = new ByteArrayInputStream(invoiceBuf);
        final AMedia amedia = new AMedia("Invoice.pdf", "pdf", "application/pdf", mediais);

        // set iframe content
        invoiceFrame = (Iframe) Path.getComponent("/win/invoiceWindow/invoiceFrame");
        invoiceFrame.setContent(amedia);
        invoiceWindow.doPopup();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * Subtract and round according to the larger of the two ulps.
 *
 * @param x The left term.// ww w  .ja  v  a  2  s  . c om
 * @param y The right term.
 * @return The difference x-y.
 */
static public BigDecimal subtractRound(final BigDecimal x, final BigDecimal y) {
    BigDecimal resul = x.subtract(y);
    /* The estimation of the absolute error in the result is |err(y)|+|err(x)|
     */

    double errR = Math.abs(y.ulp().doubleValue() / 2.) + Math.abs(x.ulp().doubleValue() / 2.);
    MathContext mc = new MathContext(err2prec(resul.doubleValue(), errR));

    return resul.round(mc);

}

From source file:com.cssweb.android.trade.util.TradeUtil.java

/**
 * ??//  www.j  a v a 2  s .  c  o m
 */
public static String formatNum(String str, int len) {
    if (str == null)
        return "";
    int flag = 1;
    if (str.charAt(0) == '-' && str.charAt(1) == '.') {
        str = str.replace("-.", "-0.");
        flag = -1;
    }
    if (str.charAt(0) == '.')
        str = "0" + str;
    if (len < 0)
        len = 0;
    BigDecimal small = new BigDecimal("0");
    BigDecimal big = new BigDecimal("0");
    if (("0").equals(str) && len == 0)
        return "0";
    if (str.indexOf(".") != -1) {
        String[] ary = str.split("\\.");
        big = BigDecimal.valueOf(Double.parseDouble(ary[0]));
        small = BigDecimal.valueOf(Double.parseDouble("0." + ary[1]));
        small = small.setScale(len > 0 ? len : 1, BigDecimal.ROUND_HALF_UP);
        if (str.charAt(0) == '-') {
            return big.subtract(small).multiply(new BigDecimal(flag)).setScale(len, BigDecimal.ROUND_HALF_UP)
                    .toString();
        }
        return big.add(small).multiply(new BigDecimal(flag)).setScale(len, BigDecimal.ROUND_HALF_UP).toString();
    } else {
        return new BigDecimal(str).multiply(new BigDecimal(flag)).setScale(len, BigDecimal.ROUND_HALF_UP)
                .toString();
    }
}

From source file:org.openbravo.advpaymentmngt.utility.APRM_MatchingUtility.java

/**
 * Merges given bank statement line with other bank statement lines with the same line number and
 * not matched with any transaction./*  w  w w  .  j av a 2 s.  co m*/
 * 
 * @param bsline
 *          Bank Statement Line.
 */
private static void mergeBankStatementLine(FIN_BankStatementLine bsline) {
    BigDecimal totalCredit = bsline.getCramount();
    BigDecimal totalDebit = bsline.getDramount();
    FIN_BankStatement bs = bsline.getBankStatement();
    OBCriteria<FIN_BankStatementLine> obc = OBDal.getInstance().createCriteria(FIN_BankStatementLine.class);
    obc.add(Restrictions.eq(FIN_BankStatementLine.PROPERTY_BANKSTATEMENT, bsline.getBankStatement()));
    obc.add(Restrictions.eq(FIN_BankStatementLine.PROPERTY_LINENO, bsline.getLineNo()));
    obc.add(Restrictions.ne(FIN_BankStatementLine.PROPERTY_ID, bsline.getId()));
    obc.add(Restrictions.isNull(FIN_BankStatementLine.PROPERTY_FINANCIALACCOUNTTRANSACTION));
    // Following list should contain just 2 elements maximum
    final List<FIN_BankStatementLine> splitLines = obc.list();

    if (!splitLines.isEmpty()) {
        // bs is set a false, because it is processed bs cannot be edited
        bs.setProcessed(false);
        OBDal.getInstance().save(bs);
        OBDal.getInstance().flush();

        for (final FIN_BankStatementLine bsl : splitLines) {
            totalCredit = totalCredit.add(bsl.getCramount());
            totalDebit = totalDebit.add(bsl.getDramount());
            OBDal.getInstance().remove(bsl);
        }

        if (totalCredit.compareTo(BigDecimal.ZERO) != 0 && totalDebit.compareTo(BigDecimal.ZERO) != 0) {
            BigDecimal total = totalCredit.subtract(totalDebit);
            if (total.compareTo(BigDecimal.ZERO) == -1) {
                bsline.setCramount(BigDecimal.ZERO);
                bsline.setDramount(total.abs());
            } else {
                bsline.setCramount(total);
                bsline.setDramount(BigDecimal.ZERO);
            }
        } else {
            bsline.setCramount(totalCredit);
            bsline.setDramount(totalDebit);
        }
        // Required to persist current bank statement line merges so that it is not rollbacked
        // afterwards because of a future error
        OBDal.getInstance().save(bsline);
        OBDal.getInstance().flush();

        // bs is set a true, because it was the status at the beginning of this function
        bs.setProcessed(true);
        OBDal.getInstance().save(bs);
        OBDal.getInstance().flush();
    }

}

From source file:org.openbravo.advpaymentmngt.actionHandler.AddPaymentActionHandler.java

private void addGLItems(FIN_Payment payment, JSONObject jsonparams) throws JSONException, ServletException {
    // Add GL Item lines
    JSONObject gLItemsGrid = jsonparams.getJSONObject("glitem");
    JSONArray addedGLITemsArray = gLItemsGrid.getJSONArray("_allRows");
    boolean isReceipt = payment.isReceipt();
    for (int i = 0; i < addedGLITemsArray.length(); i++) {
        JSONObject glItem = addedGLITemsArray.getJSONObject(i);
        BigDecimal glItemOutAmt = BigDecimal.ZERO;
        BigDecimal glItemInAmt = BigDecimal.ZERO;

        if (glItem.has("paidOut") && glItem.get("paidOut") != JSONObject.NULL) {
            glItemOutAmt = new BigDecimal(glItem.getString("paidOut"));
        }/*from   w  w  w .j  a  v a 2s .  com*/
        if (glItem.has("receivedIn") && glItem.get("receivedIn") != JSONObject.NULL) {
            glItemInAmt = new BigDecimal(glItem.getString("receivedIn"));
        }

        BigDecimal glItemAmt = BigDecimal.ZERO;
        if (isReceipt) {
            glItemAmt = glItemInAmt.subtract(glItemOutAmt);
        } else {
            glItemAmt = glItemOutAmt.subtract(glItemInAmt);
        }
        String strGLItemId = null;
        if (glItem.has("gLItem") && glItem.get("gLItem") != JSONObject.NULL) {
            strGLItemId = glItem.getString("gLItem");
            checkID(strGLItemId);
        }

        // Accounting Dimensions
        BusinessPartner businessPartnerGLItem = null;
        if (glItem.has("businessPartner") && glItem.get("businessPartner") != JSONObject.NULL) {
            final String strElement_BP = glItem.getString("businessPartner");
            checkID(strElement_BP);
            businessPartnerGLItem = OBDal.getInstance().get(BusinessPartner.class, strElement_BP);
        }
        Product product = null;
        if (glItem.has("product") && glItem.get("product") != JSONObject.NULL) {
            final String strElement_PR = glItem.getString("product");
            checkID(strElement_PR);
            product = OBDal.getInstance().get(Product.class, strElement_PR);
        }
        Project project = null;
        if (glItem.has("project") && glItem.get("project") != JSONObject.NULL) {
            final String strElement_PJ = glItem.getString("project");
            checkID(strElement_PJ);
            project = OBDal.getInstance().get(Project.class, strElement_PJ);
        }
        ABCActivity activity = null;
        if (glItem.has("cActivityDim") && glItem.get("cActivityDim") != JSONObject.NULL) {
            final String strElement_AY = glItem.getString("cActivityDim");
            checkID(strElement_AY);
            activity = OBDal.getInstance().get(ABCActivity.class, strElement_AY);
        }
        Costcenter costCenter = null;
        if (glItem.has("costCenter") && glItem.get("costCenter") != JSONObject.NULL) {
            final String strElement_CC = glItem.getString("costCenter");
            checkID(strElement_CC);
            costCenter = OBDal.getInstance().get(Costcenter.class, strElement_CC);
        }
        Campaign campaign = null;
        if (glItem.has("cCampaignDim") && glItem.get("cCampaignDim") != JSONObject.NULL) {
            final String strElement_MC = glItem.getString("cCampaignDim");
            checkID(strElement_MC);
            campaign = OBDal.getInstance().get(Campaign.class, strElement_MC);
        }
        UserDimension1 user1 = null;
        if (glItem.has("stDimension") && glItem.get("stDimension") != JSONObject.NULL) {
            final String strElement_U1 = glItem.getString("stDimension");
            checkID(strElement_U1);
            user1 = OBDal.getInstance().get(UserDimension1.class, strElement_U1);
        }
        UserDimension2 user2 = null;
        if (glItem.has("ndDimension") && glItem.get("ndDimension") != JSONObject.NULL) {
            final String strElement_U2 = glItem.getString("ndDimension");
            checkID(strElement_U2);
            user2 = OBDal.getInstance().get(UserDimension2.class, strElement_U2);
        }
        FIN_AddPayment.saveGLItem(payment, glItemAmt, OBDal.getInstance().get(GLItem.class, strGLItemId),
                businessPartnerGLItem, product, project, campaign, activity, null, costCenter, user1, user2);
    }
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * Reduce value to the interval [-Pi/2,Pi/2].
 *
 * @param x The original value//from  w  w  w . j a v  a  2 s. c o  m
 * @return The value modulo pi, shifted to the interval from -Pi/2 to Pi/2.
 */
static public BigDecimal modpi(BigDecimal x) {
    /* write x= pi*k+r with the precision in r defined by the precision of x and not
     * compromised by the precision of pi, so the ulp of pi*k should match the ulp of x.
     * First getFloat a guess of k to figure out how many digits of pi are needed.
     */
    int k = (int) (x.doubleValue() / Math.PI);
    /* want to have err(pi*k)< err(x)=x.ulp/2, so err(pi) = err(x)/(2k) with two safety digits
     */

    double errpi;

    if (k != 0) {
        errpi = 0.5 * Math.abs(x.ulp().doubleValue() / k);
    } else {
        errpi = 0.5 * Math.abs(x.ulp().doubleValue());
    }
    MathContext mc = new MathContext(2 + err2prec(3.1416, errpi));
    BigDecimal onepi = pi(mc);
    BigDecimal pihalf = onepi.divide(new BigDecimal(2));
    /* Delegate the actual operation to the BigDecimal class, which may return
     * a negative value of x was negative .
     */
    BigDecimal res = x.remainder(onepi);

    if (res.compareTo(pihalf) > 0) {
        res = res.subtract(onepi);
    } else if (res.compareTo(pihalf.negate()) < 0) {
        res = res.add(onepi);
    }
    /* The actual precision is set by the input value, its absolute value of x.ulp()/2.
     */
    mc = new MathContext(err2prec(res.doubleValue(), x.ulp().doubleValue() / 2.));

    return res.round(mc);

}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * Euler-Mascheroni constant.//from w  w w  .  j av a  2s .  com
 *
 * @param mc The required precision of the result.
 * @return 0.577...
 */
static public BigDecimal gamma(MathContext mc) {
    /* look it up if possible */
    if (mc.getPrecision() < GAMMA.precision()) {
        return GAMMA.round(mc);
    } else {
        double eps = prec2err(0.577, mc.getPrecision());
        /* Euler-Stieltjes as shown in Dilcher, Aequat Math 48 (1) (1994) 55-85
        14
         */
        MathContext mcloc = new MathContext(2 + mc.getPrecision());
        BigDecimal resul = BigDecimal.ONE;
        resul = resul.add(log(2, mcloc));
        resul = resul.subtract(log(3, mcloc));
        /* how many terms: zeta-1 falls as 1/2^(2n+1), so the
         * terms drop faster than 1/2^(4n+2). Set 1/2^(4kmax+2) < eps.
         * Leading term zeta(3)/(4^1*3) is 0.017. Leading zeta(3) is 1.2. Log(2) is 0.7
         */
        int kmax = (int) ((Math.log(eps / 0.7) - 2.) / 4.);
        mcloc = new MathContext(1 + err2prec(1.2, eps / kmax));
        for (int n = 1;; n++) {
            /* zeta is close to 1. Division of zeta-1 through
             * 4^n*(2n+1) means divion through roughly 2^(2n+1)
             */
            BigDecimal c = zeta(2 * n + 1, mcloc).subtract(BigDecimal.ONE);
            BigInteger fourn = new BigInteger("" + (2 * n + 1));
            fourn = fourn.shiftLeft(2 * n);
            c = divideRound(c, fourn);
            resul = resul.subtract(c);
            if (c.doubleValue() < 0.1 * eps) {
                break;
            }
        }
        return resul.round(mc);
    }
}

From source file:org.efaps.esjp.accounting.report.PurchaseRecordReport_Base.java

@SuppressWarnings("unchecked")
@Override//from   w w w  .  j  ava 2s .  co  m
public void init(final JasperReport _jasperReport, final Parameter _parameter, final JRDataSource _parentSource,
        final Map<String, Object> _jrParameters) throws EFapsException {
    QueryCache.cleanByKey(PurchaseRecordReport_Base.CACHEDQUERYKEY);

    final List<Map<String, Object>> values = new ArrayList<>();
    final List<Instance> instances = getInstances(_parameter);

    if (instances.size() > 0) {
        final Map<Instance, PosSum4Doc> posSums = getPosSums(_parameter);

        final SelectBuilder selRel = new SelectBuilder().linkto(CIAccounting.PurchaseRecord2Document.ToLink);
        final SelectBuilder selRelDocType = new SelectBuilder(selRel).type();
        final SelectBuilder selRelDocInst = new SelectBuilder(selRel).instance();
        final SelectBuilder selRelDocName = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.Name);
        final SelectBuilder selRelDocRevision = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.Revision);
        final SelectBuilder selRelDocDate = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.Date);
        final SelectBuilder selRelDocDueDate = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.DueDate);
        final SelectBuilder selRelDocNTotal = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.NetTotal);
        final SelectBuilder selRelDocCTotal = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.CrossTotal);
        final SelectBuilder selRelDocRNTotal = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.RateNetTotal);
        final SelectBuilder selRelDocRCTotal = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.RateCrossTotal);
        final SelectBuilder selRelDocRateLabel = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.Rate).label();

        final SelectBuilder selRelDocCurInst = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.CurrencyId).instance();
        final SelectBuilder selRelDocRCurInst = new SelectBuilder(selRel)
                .attribute(CISales.DocumentSumAbstract.RateCurrencyId).instance();

        final SelectBuilder selRelDocContact = new SelectBuilder(selRel)
                .linkto(CISales.DocumentSumAbstract.Contact);
        final SelectBuilder selRelDocContactName = new SelectBuilder(selRelDocContact)
                .attribute(CIContacts.Contact.Name);
        final SelectBuilder selRelDocContactTax = new SelectBuilder(selRelDocContact)
                .clazz(CIContacts.ClassOrganisation).attribute(CIContacts.ClassOrganisation.TaxNumber);
        final SelectBuilder selRelDocContactIdenityCard = new SelectBuilder(selRelDocContact)
                .clazz(CIContacts.ClassPerson).attribute(CIContacts.ClassPerson.IdentityCard);
        final SelectBuilder selRelDocContactDOIType = new SelectBuilder(selRelDocContact)
                .clazz(CIContacts.ClassPerson).linkto(CIContacts.ClassPerson.DOITypeLink)
                .attribute(CIContacts.AttributeDefinitionDOIType.MappingKey);

        final SelectBuilder selRelTypeLink = new SelectBuilder()
                .linkto(CIAccounting.PurchaseRecord2Document.TypeLink);
        final SelectBuilder selRelTypeLinkName = new SelectBuilder(selRelTypeLink)
                .attribute(CIERP.DocumentType.Name);

        final MultiPrintQuery multi = new MultiPrintQuery(instances);
        multi.addSelect(selRelDocType, selRelDocInst, selRelDocName, selRelDocRevision, selRelDocDate,
                selRelDocDueDate, selRelDocNTotal, selRelDocCTotal, selRelDocRNTotal, selRelDocRCTotal,
                selRelDocRateLabel, selRelDocCurInst, selRelDocRCurInst, selRelDocContactName,
                selRelDocContactTax, selRelTypeLinkName, selRelDocContactIdenityCard, selRelDocContactDOIType);
        multi.addAttribute(CIAccounting.PurchaseRecord2Document.DetractionDate,
                CIAccounting.PurchaseRecord2Document.DetractionName,
                CIAccounting.PurchaseRecord2Document.DetractionAmount,
                CIAccounting.PurchaseRecord2Document.Taxed);
        multi.execute();

        while (multi.next()) {
            final Map<String, Object> map = new HashMap<>();
            final Type docType = multi.<Type>getSelect(selRelDocType);
            final Instance instDoc = multi.<Instance>getSelect(selRelDocInst);
            final String docName = multi.<String>getSelect(selRelDocName);
            final DateTime docDate = multi.<DateTime>getSelect(selRelDocDate);
            final DateTime docDueDate = multi.<DateTime>getSelect(selRelDocDueDate);
            final String contactName = multi.<String>getSelect(selRelDocContactName);
            final String contactTaxNum = multi.<String>getSelect(selRelDocContactTax);
            final BigDecimal rateTmp = multi.<BigDecimal>getSelect(selRelDocRateLabel);
            final String typeLinkName = multi.<String>getSelect(selRelTypeLinkName);
            final String docRevision = multi.<String>getSelect(selRelDocRevision);
            final String docContactIdenityCard = multi.<String>getSelect(selRelDocContactIdenityCard);
            final String docContactDOIType = multi.<String>getSelect(selRelDocContactDOIType);
            final Taxed4PurchaseRecord taxed = multi.getAttribute(CIAccounting.PurchaseRecord2Document.Taxed);

            final String detractionName = multi
                    .<String>getAttribute(CIAccounting.PurchaseRecord2Document.DetractionName);
            final BigDecimal detractionAmount = multi
                    .<BigDecimal>getAttribute(CIAccounting.PurchaseRecord2Document.DetractionAmount);
            final DateTime detractionDate = multi
                    .<DateTime>getAttribute(CIAccounting.PurchaseRecord2Document.DetractionDate);
            final Instance docDerivatedRel = getDocumentDerivated(instDoc, true) == null
                    ? getDocumentDerivated(instDoc, false)
                    : getDocumentDerivated(instDoc, true);

            BigDecimal netTotal = multi.<BigDecimal>getSelect(selRelDocNTotal);
            BigDecimal crossTotal = multi.<BigDecimal>getSelect(selRelDocCTotal);

            final PosSum4Doc posSum = posSums.get(instDoc);
            BigDecimal taxfree;
            if (posSum != null) {
                taxfree = posSum.getTaxFree(_parameter);
            } else {
                taxfree = BigDecimal.ZERO;
            }
            BigDecimal igv = crossTotal.subtract(netTotal);
            netTotal = netTotal.subtract(taxfree);

            if (crossTotal.compareTo(netTotal) == 0) {
                taxfree = netTotal;
                netTotal = BigDecimal.ZERO;
            }

            if (CISales.IncomingCreditNote.getType().equals(docType)) {
                netTotal = netTotal.negate();
                crossTotal = crossTotal.negate();
                igv = igv.negate();
                taxfree = taxfree.negate();
            }

            PurchaseRecordReport_Base.LOG.debug("Document OID '{}'", instDoc.getOid());
            PurchaseRecordReport_Base.LOG.debug("Document name '{}'", docName);

            map.put(PurchaseRecordReport_Base.Field.DOC_RATE.getKey(), rateTmp);
            map.put(PurchaseRecordReport_Base.Field.DOC_DATE.getKey(), docDate);
            map.put(PurchaseRecordReport_Base.Field.DOC_DUEDATE.getKey(), docDueDate);
            map.put(PurchaseRecordReport_Base.Field.DOC_NAME.getKey(), docName);
            map.put(PurchaseRecordReport_Base.Field.DOC_CONTACT.getKey(), contactName);
            Boolean isDOI = false;
            String taxNum = contactTaxNum;
            if (taxNum == null || taxNum != null && taxNum.isEmpty()) {
                if (docContactIdenityCard != null && !docContactIdenityCard.isEmpty()) {
                    taxNum = docContactIdenityCard;
                    isDOI = true;
                }
            }
            map.put(PurchaseRecordReport_Base.Field.DOC_TAXNUM.getKey(), taxNum);

            switch (taxed) {
            case TAXED:
                map.put(PurchaseRecordReport_Base.Field.DOC_NETTOTALTAXED.getKey(), netTotal);
                map.put(PurchaseRecordReport_Base.Field.DOC_IGVTAXED.getKey(), igv);
                break;
            case EXPORT:
                map.put(PurchaseRecordReport_Base.Field.DOC_NETTOTALEXPORT.getKey(), netTotal);
                map.put(PurchaseRecordReport_Base.Field.DOC_IGVEXPORT.getKey(), igv);
                break;
            case UNTAXED:
                map.put(PurchaseRecordReport_Base.Field.DOC_NETTOTALUNTAXED.getKey(), netTotal);
                map.put(PurchaseRecordReport_Base.Field.DOC_IGVUNTAXED.getKey(), igv);
                break;
            default:
                break;
            }

            map.put(PurchaseRecordReport_Base.Field.DOC_CROSSTOTAL.getKey(), crossTotal);
            map.put(PurchaseRecordReport_Base.Field.DOC_VALUENOTAX.getKey(), taxfree);

            final String[] nameAr = docName.split("\\W");

            if (nameAr.length == 2 && nameAr[0].length() < nameAr[1].length()) {
                map.put(PurchaseRecordReport_Base.Field.DOC_SN.getKey(), nameAr[0]);
                map.put(PurchaseRecordReport_Base.Field.DOC_NUMBER.getKey(), nameAr[1]);
            } else {
                map.put(PurchaseRecordReport_Base.Field.DOC_SN.getKey(), "");
                map.put(PurchaseRecordReport_Base.Field.DOC_NUMBER.getKey(), docName);
            }

            map.put(PurchaseRecordReport_Base.Field.DOC_DOCTYPE.getKey(), typeLinkName);
            map.put(PurchaseRecordReport_Base.Field.DOC_REVISION.getKey(), docRevision);
            map.put(PurchaseRecordReport_Base.Field.DETRACTION_NAME.getKey(), detractionName);
            map.put(PurchaseRecordReport_Base.Field.DETRACTION_AMOUNT.getKey(), detractionAmount);
            map.put(PurchaseRecordReport_Base.Field.DETRACTION_DATE.getKey(),
                    detractionAmount == null ? null : detractionDate);

            if (docDerivatedRel != null && docDerivatedRel.isValid()) {
                final SelectBuilder selLinkName = new SelectBuilder()
                        .linkfrom(CISales.Document2DocumentType, CISales.Document2DocumentType.DocumentLink)
                        .linkto(CISales.Document2DocumentType.DocumentTypeLink)
                        .attribute(CIERP.DocumentType.Name);

                final PrintQuery printDocRel = new PrintQuery(docDerivatedRel);
                printDocRel.addAttribute(CISales.DocumentSumAbstract.Date, CISales.DocumentSumAbstract.Name);
                printDocRel.addSelect(selLinkName);
                printDocRel.execute();

                final DateTime docRelDate = printDocRel
                        .<DateTime>getAttribute(CISales.DocumentSumAbstract.Date);
                final String docRelName = printDocRel.<String>getAttribute(CISales.DocumentSumAbstract.Name);

                map.put(PurchaseRecordReport_Base.Field.DOCREL_DATE.getKey(), docRelDate);
                map.put(PurchaseRecordReport_Base.Field.DOCREL_PREFNAME.getKey(),
                        docRelName.split("-").length == 2 ? docRelName.split("-")[0] : "");
                map.put(PurchaseRecordReport_Base.Field.DOCREL_SUFNAME.getKey(),
                        docRelName.split("-").length == 2 ? docRelName.split("-")[1] : docRelName);
                map.put(PurchaseRecordReport_Base.Field.DOCREL_TYPE.getKey(),
                        printDocRel.<String>getSelect(selLinkName));
            }

            // TODO falta implementar
            map.put(PurchaseRecordReport_Base.Field.DUA_YEAR.getKey(), "0");
            map.put(PurchaseRecordReport_Base.Field.RETENCION_APPLIES.getKey(), false);

            if (isDOI) {
                map.put(PurchaseRecordReport_Base.Field.DOC_CONTACTDOI.getKey(), docContactDOIType);
            } else if (contactTaxNum.length() == 11) {
                map.put(PurchaseRecordReport_Base.Field.DOC_CONTACTDOI.getKey(), "6");
            } else {
                map.put(PurchaseRecordReport_Base.Field.DOC_CONTACTDOI.getKey(), "0");
            }

            final DateTime purchaseDate = getDate4Purchase(_parameter);
            final Integer diff = purchaseDate.getMonthOfYear() - docDate.getMonthOfYear();

            if (Math.abs(diff) > 12) {
                map.put(PurchaseRecordReport_Base.Field.DOC_STATE.getKey(), DocState.OUSIDE.getKey());
            } else if (Math.abs(diff) > 0) {
                map.put(PurchaseRecordReport_Base.Field.DOC_STATE.getKey(), DocState.INSIDE.getKey());
            } else {
                map.put(PurchaseRecordReport_Base.Field.DOC_STATE.getKey(), DocState.NORMAL.getKey());
            }

            values.add(map);
        }
    }
    final ComparatorChain chain = new ComparatorChain();
    chain.addComparator(new Comparator<Map<String, Object>>() {

        @Override
        public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) {
            final String val1 = (String) _o1.get(PurchaseRecordReport_Base.Field.DOC_DOCTYPE.getKey());
            final String val2 = (String) _o2.get(PurchaseRecordReport_Base.Field.DOC_DOCTYPE.getKey());
            return val1.compareTo(val2);
        }
    });
    chain.addComparator(new Comparator<Map<String, Object>>() {

        @Override
        public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) {
            final DateTime date1 = (DateTime) _o1.get(PurchaseRecordReport_Base.Field.DOC_DATE.getKey());
            final DateTime date2 = (DateTime) _o2.get(PurchaseRecordReport_Base.Field.DOC_DATE.getKey());
            return date1.compareTo(date2);
        }
    });
    chain.addComparator(new Comparator<Map<String, Object>>() {

        @Override
        public int compare(final Map<String, Object> _o1, final Map<String, Object> _o2) {
            final String val1 = (String) _o1.get(PurchaseRecordReport_Base.Field.DOC_NAME.getKey());
            final String val2 = (String) _o2.get(PurchaseRecordReport_Base.Field.DOC_NAME.getKey());
            return val1.compareTo(val2);
        }
    });

    Collections.sort(values, chain);
    getValues().addAll(values);
}

From source file:org.apache.calcite.runtime.SqlFunctions.java

public static BigDecimal floor(BigDecimal b0, BigDecimal b1) {
    final BigDecimal[] bigDecimals = b0.divideAndRemainder(b1);
    BigDecimal r = bigDecimals[1];
    if (r.signum() < 0) {
        r = r.add(b1);/*www  . j a v a2  s  .  com*/
    }
    return b0.subtract(r);
}

From source file:com.baidu.rigel.biplatform.tesseract.action.MetaQueryAction.java

/**
 * //from  w ww.j  av  a  2s .c  om
 * @param result
 * @param sortRecord
 * @return DataModel
 */
private DataModel tonNSetting4Chart(DataModel result, SortRecord sortRecord) {
    BigDecimal sum = BigDecimal.ZERO;
    for (BigDecimal tmp : result.getColumnBaseData().get(0)) {
        //TODO ??
        if (tmp == null) {
            continue;
        }
        sum = sum.add(tmp);
    }
    // 
    result = DataModelUtils.truncModel(result, sortRecord.getRecordSize() - 1);
    BigDecimal sum1 = BigDecimal.ZERO;
    for (BigDecimal tmp : result.getColumnBaseData().get(0)) {
        //TODO ??
        if (tmp == null) {
            continue;
        }
        sum1 = sum1.add(tmp);
    }
    BigDecimal other = null;
    if (sum1 != BigDecimal.ZERO) {
        other = sum.subtract(sum1);
    }
    result.getColumnBaseData().get(0).add(other);
    HeadField otherRowField = DeepcopyUtils.deepCopy(result.getRowHeadFields().get(0));
    otherRowField.setSummarizeData(other);
    String caption = "";
    otherRowField.setCaption(caption);
    String dimName = MetaNameUtil.getDimNameFromUniqueName(otherRowField.getValue());
    String uniqueName = "[" + dimName + "].[" + caption + "]";
    String nodeUniqueName = "{" + uniqueName + "}";
    otherRowField.setNodeUniqueName(nodeUniqueName);
    otherRowField.setValue(uniqueName);
    result.getRowHeadFields().add(otherRowField);
    return result;
}