Example usage for java.math BigDecimal signum

List of usage examples for java.math BigDecimal signum

Introduction

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

Prototype

public int signum() 

Source Link

Document

Returns the signum function of this BigDecimal .

Usage

From source file:org.opentaps.dataimport.CustomerDecoder.java

/**
 * Whether we should create a sales agreement for this record.  Overload if the details vary.
 * In the case of vanilla importCustomers, an agreement is created for a credit limit, a net
 * payment days term, or both.//w ww .j  a va2s  . c om
 */
public boolean canCreateSalesAgreement(GenericValue entry) {
    BigDecimal creditLimit = entry.getBigDecimal("creditLimit");
    Long netPaymentDays = entry.getLong("netPaymentDays");

    // make the logic simpler by normalizing null to 0
    if (creditLimit == null) {
        creditLimit = BigDecimal.ZERO;
    }
    if (netPaymentDays == null)
        netPaymentDays = 0L;

    return (creditLimit.signum() > 0 || netPaymentDays > 0);
}

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);/*w  w w  . j a v a 2  s .  c o m*/
    }
    return b0.subtract(r);
}

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

public static BigDecimal ceil(BigDecimal b0, BigDecimal b1) {
    final BigDecimal[] bigDecimals = b0.divideAndRemainder(b1);
    BigDecimal r = bigDecimals[1];
    if (r.signum() > 0) {
        r = r.subtract(b1);/*from  ww  w.ja v  a  2s  . c o  m*/
    }
    return b0.subtract(r);
}

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

/** SQL <code>SIGN</code> operator applied to BigDecimal values. */
public static BigDecimal sign(BigDecimal b0) {
    return BigDecimal.valueOf(b0.signum());
}

From source file:org.efaps.esjp.accounting.transaction.Transaction_Base.java

/**
 * @param _parameter Parameter as passed from eFaps API
 * @param _instance insatcne to be checked
 * @param _amounts  amounts to be checked
 * @return true if valid else false// w  w  w  .  ja  v  a  2  s  .c o  m
 * @throws EFapsException on error
 */
protected boolean validateAmounts4EditTransactionPos(final Parameter _parameter, final Instance _instance,
        final String... _amounts) throws EFapsException {
    final DecimalFormat formatter = NumberFormatter.get().getFormatter(null, 2);

    boolean ret = true;

    if (_amounts != null && _amounts.length > 0) {
        for (final String amountStr : _amounts) {
            try {
                final BigDecimal amount = (BigDecimal) formatter.parse(amountStr);
                if (CIAccounting.TransactionPositionCredit.getType().equals(_instance.getType())) {
                    if (amount.signum() < 0) {
                        ret = false;
                        break;
                    }
                } else if (CIAccounting.TransactionPositionDebit.getType().equals(_instance.getType())) {
                    if (amount.signum() > 0) {
                        ret = false;
                        break;
                    }
                }
            } catch (final ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    return ret;
}

From source file:com.autentia.intra.bean.account.AccountEntryBean.java

private void calcTotals(List<AccountEntry> res) {
    costs = new BigDecimal(0);
    incomes = new BigDecimal(0);

    costsType = new BigDecimal(0);
    incomesType = new BigDecimal(0);

    Hashtable mapaCajaTotales = new Hashtable();

    for (AccountEntry elem : res) {
        Integer accountAct = elem.getAccount().getId();
        BigDecimal accountValueAct = null;
        if (!mapaCajaTotales.containsKey(accountAct)) {
            mapaCajaTotales.put(accountAct, new BigDecimal(0));
        }// w w  w .j  av  a  2  s.com

        accountValueAct = (BigDecimal) mapaCajaTotales.get(accountAct);

        BigDecimal actual = elem.getAmount();
        BigDecimal resul = accountValueAct.add(actual);
        elem.setAmountAccountNow(resul);
        mapaCajaTotales.remove(accountAct);
        mapaCajaTotales.put(accountAct, resul);

        if (actual.signum() >= 0) {
            setIncomes(incomes.add(actual));
        } else {
            setCosts(costs.add(actual));
        }

        if (elem.getType().getGroup().getId() == ConfigurationUtil.getDefault().getCostId()) {
            setCostsType(costsType.add(actual));
        } else {
            setIncomesType(incomesType.add(actual));
        }
    }

    setTotal(incomes.add(costs));
    setTotalType(incomesType.add(costsType));
}

From source file:org.opentaps.common.util.UtilCommon.java

/**
 * Assuming theMap not null; if null will throw a NullPointerException.
 * @param <K> the key type/*from  w  w  w.  ja v  a2  s  . c om*/
 * @param theMap the <code>Map<K, BigDecimal></code> where to add the value
 * @param mapKey the key in the map where to add the value
 * @param addNumber the value to add in the map (can be null)
 * @return the new value for the given key in the map, after the value is added
 */
public static <K> BigDecimal addInMapOfBigDecimal(Map<K, BigDecimal> theMap, K mapKey, BigDecimal addNumber) {
    BigDecimal currentNumber = theMap.get(mapKey);
    if (currentNumber == null) {
        currentNumber = BigDecimal.ZERO;
    }

    if (addNumber == null || addNumber.signum() == 0) {
        return currentNumber;
    }
    currentNumber = currentNumber.add(addNumber);
    theMap.put(mapKey, currentNumber);
    return currentNumber;
}

From source file:org.openmrs.module.billing.web.controller.billingqueuedia.BillingService.java

@RequestMapping(value = "/module/billing/orderStoreSave.form", method = RequestMethod.POST)
public String billSaveOrder(@RequestParam("patientId") Integer patientId,
        @RequestParam(value = "refDocId", required = false) Integer refDocId,
        @RequestParam(value = "refMarId", required = false) Integer refMarId,
        @RequestParam(value = "orderId", required = false) Integer orderId,
        @RequestParam(value = "refRmpId", required = false) Integer refRmpId,
        @RequestParam(value = "dDate", required = false) String dDate,
        @RequestParam(value = "dTime", required = false) String dTime,
        @RequestParam(value = "rem", required = false) String remarks,
        //  @RequestParam(value = "discount", required = false) BigDecimal discount,
        @RequestParam(value = "discount", required = false) String discount,
        @RequestParam("indCount") Integer indCount,
        @RequestParam(value = "encounterId", required = false) String encounterId, HttpServletRequest request,
        Model model) throws ParseException, Exception {

    Patient patient = Context.getPatientService().getPatient(patientId);

    MedisunService ms = Context.getService(MedisunService.class);
    org.openmrs.module.hospitalcore.BillingService billingService = Context
            .getService(org.openmrs.module.hospitalcore.BillingService.class);

    //Date birthday = patient.getBirthdate();
    // model.addAttribute("age", PatientUtils.estimateAge(birthday));
    String fullPaid = request.getParameter("paid");
    String fullFree = request.getParameter("free");
    String freeReason = request.getParameter("freeReason");
    BigDecimal doctorGivenPer = NumberUtils.createBigDecimal(request.getParameter("docGivPer"));
    BigDecimal p = new BigDecimal("0.00");
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date deDate = null;//from w  w  w.  j  a  va  2s. co  m

    if (StringUtils.isNotBlank(dDate)) {
        deDate = sdf.parse(dDate);
    }
    //        System.out.println("***********ddddd"+doctorGivenPer);
    //        if (doctorGivenPer == null) {
    //            doctorGivenPer=p;
    //        }
    //        else{
    //            doctorGivenPer=doctorGivenPer;
    //        }
    //                
    DiaBillingQueue dbq = ms.getDiaBillingQueue(orderId);

    DiaReceipt dr = new DiaReceipt();
    dr.setPaidDate(new Date());
    dr.setDeliveryDate(deDate);
    dr.setDeliveryTime(dTime);
    dr.setServiceId(orderId);
    dr.setDoctorGiven(doctorGivenPer); //
    ms.saveDiaReceipt(dr);

    User user = Context.getAuthenticatedUser();

    BillableService service;

    BigDecimal totalBill = NumberUtils.createBigDecimal(request.getParameter("totalBill"));
    BigDecimal netAmount = NumberUtils.createBigDecimal(request.getParameter("netamount"));

    BigDecimal paidAmount = NumberUtils.createBigDecimal(request.getParameter("paidamount"));
    BigDecimal payableAmount = NumberUtils.createBigDecimal(request.getParameter("payableamount"));
    BigDecimal dueAmount = NumberUtils.createBigDecimal(request.getParameter("dueamount"));
    BigDecimal discountAmount = NumberUtils.createBigDecimal(request.getParameter("discountamount"));
    BigDecimal unitPrice = NumberUtils.createBigDecimal(request.getParameter("unitprice"));
    // BigDecimal discount = NumberUtils.createBigDecimal(request.getParameter("discount"));

    if (paidAmount == null) {
        paidAmount = p;
    } else {
        paidAmount = paidAmount;
    }

    String due = null;
    boolean status;
    if ((StringUtils.equals(fullPaid, "1")) && (dueAmount.signum() < 1)) {
        due = "PAID";
        status = false;
        totalBill = totalBill;
    } else if ((StringUtils.equals(fullPaid, null)) && (StringUtils.equals(fullFree, null))
            && (dueAmount.signum() < 1)) {
        due = "PAID";
        status = false;
        totalBill = totalBill;
    } else if ((!StringUtils.equalsIgnoreCase(fullFree, null))) {
        due = "FREE";
        status = true;
        totalBill = p;
    } else {
        due = "DUE";
        status = false;
        totalBill = totalBill;
    }

    DiaPatientServiceBill dpsb = new DiaPatientServiceBill();
    dpsb.setPatient(patient);
    dpsb.setCreatedDate(new Date());
    dpsb.setCreator(user);
    dpsb.setAmount(netAmount);
    dpsb.setPrinted(Boolean.FALSE);
    dpsb.setReceipt(dr);
    dpsb.setVoided(Boolean.FALSE);
    dpsb.setActualAmount(totalBill); /// if free actual amount is 0.00
    dpsb.setDueAmount(dueAmount);
    dpsb.setBillingStatus(due);
    dpsb.setRefDocId(refDocId);
    dpsb.setRefMarId(refMarId);
    dpsb.setRefRmpId(refRmpId);
    dpsb.setComment(remarks);
    dpsb.setDiscountAmount(discountAmount);
    dpsb.setFreeReason(freeReason);
    //if (paidAmount.signum() > 0) {
    dpsb = ms.saveDiaPatientServiceBill(dpsb);
    //}

    // if (dpsb != null && dpsb.getBillId() != null ) {
    if (dpsb != null && dpsb.getBillId() != null && orderId != 0) {
        ms.removeDiaBillingQueue(dbq);
    }
    model.addAttribute("billId", dpsb.getBillId());
    model.addAttribute("orderId", orderId);
    model.addAttribute("refDocId", refDocId);
    model.addAttribute("refRmpId", refRmpId);
    model.addAttribute("paid", paidAmount);
    model.addAttribute("dDate", dDate);
    model.addAttribute("dTime", dTime);

    DiaPatientServiceBillCollect dBillColl = new DiaPatientServiceBillCollect();
    dBillColl.setPatientId(patientId);
    dBillColl.setDiaPatientServiceBill(dpsb);
    dBillColl.setUser(user);
    dBillColl.setCreatedDate(new Date());
    dBillColl.setActualAmount(totalBill);
    dBillColl.setPaidAmount(paidAmount);
    dBillColl.setPayableAmount(netAmount);
    dBillColl.setDueAmount(dueAmount);
    dBillColl.setDiscountAmount(discountAmount);
    dBillColl.setDuePaidStatus(status);
    dBillColl.setDuePaid(0);
    //if (paidAmount.signum() > 0) {
    ms.saveDiaPatientServiceBillCollect(dBillColl);
    //}

    String sername = null;
    BigDecimal totCom = BigDecimal.ZERO;
    BigDecimal servicePrice = BigDecimal.ZERO;

    for (Integer i = 1; i <= indCount; i++) {

        String servicename = request.getParameter("service");
        unitPrice = NumberUtils.createBigDecimal(request.getParameter(i.toString() + "unitprice")); // Quantity * unitPrice
        BigDecimal serviceprice = NumberUtils
                .createBigDecimal(request.getParameter(i.toString() + "serviceprice")); // Unit Price

        Integer qty = NumberUtils.createInteger(request.getParameter(i.toString() + "servicequantity")); // Quantity
        servicename = request.getParameter(i.toString() + "service");
        service = billingService.getServiceByConceptName(servicename);

        if (((!StringUtils.equalsIgnoreCase(service.getCategory().getId().toString(), "5678")))) {
            sername = servicename + "," + sername; // for commison

            servicePrice = servicePrice.add(unitPrice);
        }

        DiaPatientServiceBillItem dBillItem = new DiaPatientServiceBillItem();
        dBillItem.setService(service);
        dBillItem.setDiaPatientServiceBill(dpsb);
        dBillItem.setUnitPrice(serviceprice);
        dBillItem.setAmount(unitPrice);
        dBillItem.setQuantity(qty);
        dBillItem.setName(servicename);
        dBillItem.setCreatedDate(new Date());
        dBillItem.setCreator(user.getId());
        dBillItem.setVoided(Boolean.FALSE);
        dBillItem.setActualAmount(unitPrice);
        // if (paidAmount.signum() > 0) {
        ms.saveDiaPatientServiceBillItem(dBillItem);
        //}

        BigDecimal ind = NumberUtils.createBigDecimal(indCount.toString());
        BigDecimal da = discountAmount.divide(ind, 2, RoundingMode.CEILING);

        BigDecimal oneHundred = new BigDecimal(100);

        BigDecimal le = null;
        if (!StringUtils.isBlank(discount)) {
            BigDecimal dis;
            dis = new BigDecimal(discount);
            BigDecimal less = (unitPrice.multiply(dis)).divide(oneHundred, 0, RoundingMode.HALF_EVEN);
            le = less;
        } else {
            le = new BigDecimal(0);
        }

        //BigDecimal less = (unitPrice.multiply(discount)).divide(oneHundred, 0, RoundingMode.HALF_EVEN);
        if (dpsb.getBillingStatus() == "PAID") {
            if ((!StringUtils.equalsIgnoreCase(service.getCategory().getId().toString(), "5678"))) {
                DiaCommissionCal diaComCal = new DiaCommissionCal();
                diaComCal.setDiaPatientServiceBill(dpsb);
                diaComCal.setPatient(patient);
                diaComCal.setServiceName(service.getName());
                diaComCal.setServiceId(service.getServiceId());
                diaComCal.setServicePrice(serviceprice);
                //diaComCal.setLessAmount(discountAmount);
                diaComCal.setLessAmount(le);
                diaComCal.setCommission(service.getCommission());
                diaComCal.setCreatedDate(new Date());
                diaComCal.setCreator(user.getId());
                diaComCal.setRefId(dpsb.getRefDocId());
                diaComCal.setRefRmpId(dpsb.getRefRmpId());
                diaComCal.setHsStatus(Boolean.FALSE);
                ms.saveDiaComCal(diaComCal);
            }
        }

        DiaLabSampleid dls = new DiaLabSampleid();
        dls.setPatient(patient);
        dls.setDiaPatientServiceBill(dpsb);
        dls.setSampleId(generateBarcode());
        ms.saveDiaLabSam(dls);

    }

    if (sername != null && dpsb.getBillingStatus() == "PAID") {
        sername = sername.replace(",null", "");

        DiaCommissionCalAll diaAll = new DiaCommissionCalAll();
        diaAll.setDiaPatientServiceBill(dpsb);
        diaAll.setPatient(patient);
        //diaAll.setServiceName(sername);
        diaAll.setServicePrice(servicePrice);
        diaAll.setLessAmount(discountAmount);
        diaAll.setComAmount(totCom);
        diaAll.setCreatedDate(new Date());
        diaAll.setCreator(Context.getAuthenticatedUser().getId());
        diaAll.setRefId(refDocId);
        diaAll.setRefRmp(refRmpId);
        diaAll.setRefMar(refMarId);
        ms.saveDiaComAll(diaAll);
    }

    //// Generate Patient Id Barcode4j
    Code128Bean cod = new Code128Bean();
    final int reso = 128;
    cod.setModuleWidth(UnitConv.in2mm(1.0f / reso)); //makes the narrow bar 
    //width exactly one pixel
    cod.setHeight(10);
    cod.setFontSize(3);
    cod.setFontName("Times New Roman");
    // cod.doQuietZone(true);
    cod.getBarWidth(2);
    // bean.setVerticalQuietZone(1);
    cod.setMsgPosition(HumanReadablePlacement.HRP_BOTTOM);

    File outputFilePatId = new File(
            request.getSession().getServletContext().getRealPath("/barcode/" + patient.getId() + ".png"));
    // File outputFilePatId = new File("C:\\tomcat6\\webapps\\MEDISUN_HEALTH_CARE_V2_Final\\barcode/" + patient.getId() + ".png"); //Mostofa bhi

    OutputStream out1 = new FileOutputStream(outputFilePatId);
    try {
        BitmapCanvasProvider canvas = new BitmapCanvasProvider(out1, "image/x-png", reso,
                BufferedImage.TYPE_BYTE_BINARY, false, 0);

        cod.generateBarcode(canvas, patient.getPatientIdentifier().getIdentifier());

        canvas.finish();
    } finally {
        out1.close();
    }

    //// Generate Bill Id Barcode4j
    Code128Bean codBil = new Code128Bean();
    final int resou = 128;
    codBil.setModuleWidth(UnitConv.in2mm(1.0f / resou)); //makes the narrow bar 
    //width exactly one pixel
    codBil.setHeight(10);
    codBil.setFontSize(2);
    codBil.setFontName("Helvetica");
    // cod.doQuietZone(true);
    codBil.getBarWidth(2);
    // bean.setVerticalQuietZone(1);
    codBil.setMsgPosition(HumanReadablePlacement.HRP_BOTTOM);

    //  File outputFileBillId = new File("C:\\tomcat6\\webapps\\MEDISUN_HEALTH_CARE_V2_Final\\barcode/" + dpsb.getBillId() + ".png"); // Mostofa bhi
    File outputFileBillId = new File(
            request.getSession().getServletContext().getRealPath("/barcode/" + dpsb.getBillId() + ".png"));

    OutputStream outB = new FileOutputStream(outputFileBillId);
    try {
        BitmapCanvasProvider canvas = new BitmapCanvasProvider(outB, "image/x-png", reso,
                BufferedImage.TYPE_BYTE_BINARY, false, 0);

        codBil.generateBarcode(canvas, dpsb.getBillId().toString());

        canvas.finish();
    } finally {
        outB.close();
    }

    ///// End 
    model.addAttribute("discountAount", dBillColl.getDiscountAmount());

    return "redirect:/module/billing/billprint.htm?patientId=" + patientId;
    //module/billing/directbillingqueue.form

}

From source file:org.opentaps.common.util.UtilCommon.java

/**
 * Given a set of values, calculates the correspondent % of total.
 *
 * @param values a <code>Map</code> of values, such as customer/vendor balance values
 * @param minPercentage the minimum percentage to consider for calculation purposes
 * @param locale the <code>Locale</code> used to build the label strings
 * @return returns the weight (percentage) of each balance
 *///from  ww w.  j a  v a 2 s  . c o m
public static List<Map<String, Number>> getPercentageValues(Map<String, BigDecimal> values,
        BigDecimal minPercentage, Locale locale) {

    Collection<BigDecimal> inValues = values.values();
    Set<String> keys = values.keySet();
    List<Map<String, Number>> list = new LinkedList<Map<String, Number>>();
    BigDecimal total = BigDecimal.ZERO;
    BigDecimal othersTotal = BigDecimal.ZERO;
    final int decimals = 2; // precision for the percentage values

    // total up all the values
    for (BigDecimal value : inValues) {
        total = total.add(value);
    }

    if (total.signum() > 0) { //prevent division by zero
        for (String key : keys) {
            BigDecimal value = values.get(key);
            value = value.divide(total, 10, RoundingMode.HALF_UP);
            if (value.compareTo(minPercentage) == 1) { //greater than minPercentage?
                Map<String, Number> map = FastMap.newInstance();
                value = value.multiply(new BigDecimal(100)).setScale(decimals, RoundingMode.HALF_UP); //display only 2 decimal places
                map.put(key, value);
                list.add(map);
            } else {
                othersTotal = othersTotal.add(value).setScale(decimals + 3, RoundingMode.HALF_UP);
            }
        }

        // normalize to % - ie 0.577 to 57.7
        othersTotal = othersTotal.multiply(new BigDecimal(100)).setScale(decimals, RoundingMode.HALF_UP);
        if (othersTotal.signum() > 0) {
            list.add(UtilMisc.<String, Number>toMap(UtilMessage.expandLabel("CommonOther", locale)
                    + String.format(" (%1$s%%)", othersTotal.toString()), othersTotal));
        }
    }

    return list;
}

From source file:org.opentaps.dataimport.CustomerDecoder.java

/**
 * Helper function to generate a credit limit term.  Only creates term if the credit limit is positive.
 * Used by createSalesAgreementTerms().//from w  w w.  j  av a2s. co  m
 */
public List<GenericValue> createAgreementCreditLimitTerm(String agreementId, String customerCurrencyUomId,
        int seqId, Delegator delegator, BigDecimal creditLimit) {
    // get currency for customer record or from opentaps.properties
    // TODO why not just throw an illegal argument exception and have the importer fix the data?
    if (UtilValidate.isEmpty(customerCurrencyUomId)) {
        customerCurrencyUomId = UtilProperties.getPropertyValue("opentaps", "defaultCurrencyUomId");
        Debug.logWarning("No currency specified for credit limit of agreement [" + agreementId + "], using ["
                + customerCurrencyUomId + "] from opentaps.properties", MODULE);
    }
    if (creditLimit != null && creditLimit.signum() > 0) {
        return createAgreementTerm(agreementId, "AGREEMENT_CREDIT", "CREDIT_LIMIT", creditLimit, null,
                customerCurrencyUomId, seqId, delegator);
    }
    return new FastList<GenericValue>();
}