Example usage for java.math BigDecimal toString

List of usage examples for java.math BigDecimal toString

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns the string representation of this BigDecimal , using scientific notation if an exponent is needed.

Usage

From source file:org.openvpms.esci.adapter.map.invoice.InvoiceMapperImpl.java

/**
 * Verifies that the invoice line's <em>BaseQuantity</em> is specified correctly, if present.
 *
 * @param line     the invoice line/*from   w ww .  jav  a  2 s.  c o m*/
 * @param unitCode the expected unit code
 */
private void checkBaseQuantity(UBLInvoiceLine line, String unitCode) {
    BigDecimal quantity = line.getBaseQuantity();
    if (quantity != null) {
        if (quantity.compareTo(BigDecimal.ONE) != 0) {
            ErrorContext context = new ErrorContext(line, "BaseQuantity");
            throw new ESCIAdapterException(ESCIAdapterMessages.ublInvalidValue(context.getPath(),
                    context.getType(), context.getID(), "1", quantity.toString()));
        }
        String baseQuantityUnitCode = line.getBaseQuantityUnitCode();
        if (!StringUtils.equals(unitCode, baseQuantityUnitCode)) {
            ErrorContext context = new ErrorContext(line, "BaseQuantity@unitCode");
            throw new ESCIAdapterException(ESCIAdapterMessages.ublInvalidValue(context.getPath(),
                    context.getType(), context.getID(), unitCode, baseQuantityUnitCode));
        }
    }
}

From source file:org.kuali.kpme.pm.position.web.PositionMaintainableServiceImpl.java

private boolean validatePositionResponsibilityListPercentage(PositionResponsibilityBo pd,
        PositionBo aPosition) {//ww  w. j  a  v  a2  s .c  o  m
    if (CollectionUtils.isNotEmpty(aPosition.getPositionResponsibilityList()) && pd.getPercentTime() != null) {
        BigDecimal sum = pd.getPercentTime();
        for (PositionResponsibilityBo aResponsibility : aPosition.getPositionResponsibilityList()) {
            if (aResponsibility != null && aResponsibility.getPercentTime() != null) {
                sum = sum.add(aResponsibility.getPercentTime());
            }
        }
        if (sum.compareTo(new BigDecimal(100)) > 0) {
            GlobalVariables.getMessageMap().putError(
                    "newCollectionLines['document.newMaintainableObject.dataObject.positionResponsibilityList'].percentTime",
                    "responsibility.percenttime.exceedsMaximum", sum.toString());
            return false;
        }
    }
    return true;
}

From source file:org.openvpms.esci.adapter.map.invoice.InvoiceMapperImpl.java

/**
 * Maps a charge to a delivery item./*  www.j  ava  2s .c  o m*/
 *
 * @param charge    the allowance/charge
 * @param startTime the invoice start time
 * @param invoiceId the invoice identifier
 * @param rates     the tax rates
 * @return a new delivery item
 * @throws ESCIAdapterException if the allowance/charge cannot be mapped
 */
protected FinancialAct mapCharge(UBLAllowanceCharge charge, Date startTime, String invoiceId, TaxRates rates) {
    if (!charge.isCharge()) {
        throw new ESCIAdapterException(ESCIAdapterMessages.invoiceAllowanceNotSupported(invoiceId));
    }
    BigDecimal unitPrice = charge.getAmount();
    ActBean deliveryItem = factory.createActBean(SupplierArchetypes.DELIVERY_ITEM);
    BigDecimal tax = charge.getTaxAmount();
    BigDecimal rate = checkTaxCategory(charge.getTaxCategory(), rates);
    BigDecimal divisor = BigDecimal.valueOf(100);
    if (tax.compareTo(BigDecimal.ZERO) != 0) {
        BigDecimal expectedTax = MathRules.divide(unitPrice.multiply(rate), divisor, 2);
        if (expectedTax.compareTo(tax) != 0) {
            ErrorContext context = new ErrorContext(charge, "TaxTotal/TaxAmount");
            throw new ESCIAdapterException(ESCIAdapterMessages.ublInvalidValue(context.getPath(),
                    context.getType(), context.getID(), expectedTax.toString(), tax.toString()));
        }
    }
    deliveryItem.setValue("startTime", startTime);
    deliveryItem.setValue("quantity", BigDecimal.ONE);
    deliveryItem.setValue("packageUnits", null); // override default
    deliveryItem.setValue("unitPrice", unitPrice);
    deliveryItem.setValue("tax", tax);
    deliveryItem.setValue("reorderDescription", charge.getAllowanceChargeReason()); // TODO - not ideal

    getArchetypeService().deriveValues(deliveryItem.getObject());
    return (FinancialAct) deliveryItem.getAct();
}

From source file:org.kuali.rice.kew.docsearch.xml.StandardGenericXMLSearchableAttributeRangesTest.java

@Test
public void testFloatRanges() throws Exception {
    WorkflowDocument doc = setUpSearchableDoc();
    String userId = doc.getInitiatorPrincipalId();
    String docType = doc.getDocumentTypeName();

    String searchAttributeFloatKey = TestXMLSearchableAttributeFloat.SEARCH_STORAGE_KEY;
    BigDecimal searchAttributeFloatValue = TestXMLSearchableAttributeFloat.SEARCH_STORAGE_VALUE;

    BigDecimal floatValueToUse = null;
    // test lower bound only
    floatValueToUse = searchAttributeFloatValue; // lower bound == value
    // NOTE: original test asserted 0 results, mysql actually does match the value
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey, floatValueToUse.toString(), null, false,
            1);//from   www .j  a va2  s.  c  o  m

    floatValueToUse = searchAttributeFloatValue.subtract(BigDecimal.ONE); // lowerbound < value
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey, floatValueToUse.toString(), null, false,
            1);

    floatValueToUse = searchAttributeFloatValue.add(BigDecimal.ONE); // lowerbound > value
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey, floatValueToUse.toString(), null, false,
            0);

    // test upper bound only
    floatValueToUse = searchAttributeFloatValue; // upperbound == value (does not match float)
    // NOTE: another case where original test had 0 results, but in fact we see a float match
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey, null, floatValueToUse.toString(), true,
            1);

    floatValueToUse = searchAttributeFloatValue.subtract(BigDecimal.ONE); // upperbound < value
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey, null, floatValueToUse.toString(), true,
            0);

    floatValueToUse = searchAttributeFloatValue.add(BigDecimal.ONE); // upperbound > value
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey, null, floatValueToUse.toString(), true,
            1);

    // test both bounds
    // upper == lower == value
    // NOTE: original case had 0 results, now seeing 1 result
    // search generator invokes criteria which calls addNumericRangeCriteria when produces: (EXT1.VAL BETWEEN 123456.3456 AND 123456.3456)
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey, searchAttributeFloatValue.toString(),
            searchAttributeFloatValue.toString(), true, 1);

    // upper and lower > value
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey,
            searchAttributeFloatValue.add(new BigDecimal(2)).toString(),
            searchAttributeFloatValue.add(new BigDecimal(4)).toString(), true, 0);

    // upper and lower < value
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey,
            searchAttributeFloatValue.subtract(new BigDecimal(4)).toString(),
            searchAttributeFloatValue.subtract(new BigDecimal(2)).toString(), true, 0);

    // lower < value, upper > value
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey,
            searchAttributeFloatValue.subtract(new BigDecimal(2)).toString(),
            searchAttributeFloatValue.add(new BigDecimal(2)).toString(), true, 1);

    // upper < lower
    assertRangeSearchResults(docType, userId, searchAttributeFloatKey,
            searchAttributeFloatValue.add(new BigDecimal(2)).toString(),
            searchAttributeFloatValue.subtract(new BigDecimal(2)).toString(), true, EXPECT_EXCEPTION);
}

From source file:fr.univlorraine.mondossierweb.controllers.ListeInscritsController.java

private boolean listeContient(List<BigDecimal> lcodindinscrits, String cod_ind) {
    if (lcodindinscrits.size() > 0 && cod_ind != null) {
        for (BigDecimal s : lcodindinscrits) {
            if (s.toString().equals(cod_ind)) {
                return true;
            }//  ww w .  ja  v a  2 s.co  m
        }
    }
    return false;
}

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

/** CAST(DECIMAL AS VARCHAR). */
public static String toString(BigDecimal x) {
    final String s = x.toString();
    if (s.startsWith("0")) {
        // we want ".1" not "0.1"
        return s.substring(1);
    } else if (s.startsWith("-0")) {
        // we want "-.1" not "-0.1"
        return "-" + s.substring(2);
    } else {/*from   w w w  .j  a v a  2  s  .co m*/
        return s;
    }
}

From source file:org.egov.egf.web.actions.budget.BaseBudgetDetailAction.java

public List<BudgetAmountView> populateAmountData(final List<BudgetDetail> budgetDetails, final Date asOnDate,
        final CFinancialYear finYear) {
    final List<BudgetAmountView> list = new ArrayList<BudgetAmountView>();
    Map<String, Object> paramMap;
    final Long finYearId = finYear.getId();
    final List<AppConfigValues> appList = appConfigValueService.getConfigValuesByModuleAndKey(
            FinancialConstants.MODULE_NAME_APPCONFIG, FinancialConstants.APPCONFIG_COA_MAJORCODE_LENGTH);
    if (appList.isEmpty())
        throw new ValidationException(StringUtils.EMPTY, "coa.majorcode.not.defined");
    final int majorcodelength = Integer.valueOf(appList.get(0).getValue());
    final List<AppConfigValues> appListExcludeStatus = appConfigValueService.getConfigValuesByModuleAndKey(
            FinancialConstants.MODULE_NAME_APPCONFIG, FinancialConstants.APPCONFIG_EXCLUDE_STATUS);
    if (appListExcludeStatus.isEmpty())
        throw new ValidationException(StringUtils.EMPTY, "exclude.status.not.defined");

    final CFinancialYear finyear = financialYearService.getFinancialYearByDate(asOnDate);

    final Date fromdate = finyear.getStartingDate();
    final String voucherstatusExclude = appListExcludeStatus.get(0).getValue();
    for (final BudgetDetail detail : budgetDetails) {
        paramMap = budgetDetailHelper.constructParamMap(getValueStack(), detail);
        paramMap.put("MAJORCODELENGTH", majorcodelength);
        paramMap.put("VOUCHERSTATUSEXCLUDE", voucherstatusExclude);
        paramMap.put("FYFROMDATE", fromdate);
        final BudgetAmountView view = new BudgetAmountView();
        budgetDetailHelper.populateData(view, paramMap, asOnDate, re);
        final BudgetDetail detailWithoutBudget = new BudgetDetail();
        detailWithoutBudget.copyFrom(detail);
        detailWithoutBudget.setBudget(null);
        final List<BudgetDetail> bd = budgetDetailService.searchByCriteriaWithTypeAndFY(finYearId, "BE",
                detailWithoutBudget);//from   ww  w .ja va 2s  .c o  m
        if (!bd.isEmpty()) {
            final BigDecimal approvedAmount = bd.get(0).getApprovedAmount();
            view.setCurrentYearBeApproved(
                    approvedAmount == null ? BigDecimal.ZERO.toString() : approvedAmount.toString());
            view.setReappropriation(bd.get(0).getApprovedReAppropriationsTotal().toString());
        }
        view.setTotal(new BigDecimal(view.getCurrentYearBeApproved())
                .add(new BigDecimal(view.getReappropriation())).toString());
        list.add(view);
    }
    return list;
}

From source file:org.ojai.json.impl.JsonDocumentBuilder.java

@Override
public JsonDocumentBuilder put(String field, BigDecimal value) {
    try {/*from www  .  j a  v a 2  s. c  o m*/
        preparePut();
        if (jsonOptions.isWithTags()) {
            putNewMap(field);
            jsonGenerator.writeStringField(Types.TAG_DECIMAL, value.toString());
            endMap();
        } else {
            jsonGenerator.writeNumberField(field, value);
        }
        return this;
    } catch (IOException ie) {
        throw transformIOException(ie);
    }
}

From source file:org.jasig.ssp.service.impl.EvaluatedSuccessIndicatorServiceImpl.java

private Pair<Object, String> findGpaMetric(@Nonnull SuccessIndicator successIndicator, @Nonnull Person person) {
    final ExternalStudentTranscript transcript = findTranscriptFor(person);
    BigDecimal gpa = null;
    if (transcript != null) {
        gpa = transcript.getGradePointAverage();
    }//from  w  ww.  j  a  v  a 2 s.c o m
    return new Pair<Object, String>(gpa, (gpa == null ? null : gpa.toString()));
}

From source file:org.openbravo.erpCommon.ad_forms.Fact.java

/**
 * Create and convert Fact Line. Used to create either a DR or CR entry
 * /* w  ww. j  a v  a2s .  co  m*/
 * @param docLine
 *          Document Line or null
 * @param accountDr
 *          Account to be used if Amt is DR balance
 * @param accountCr
 *          Account to be used if Amt is CR balance
 * @param C_Currency_ID
 *          Currency
 * @param Amt
 *          if negative Cr else Dr
 * @return FactLine
 */
public FactLine createLine(DocLine docLine, Account accountDr, Account accountCr, String C_Currency_ID,
        String Amt, String Fact_Acct_Group_ID, String SeqNo, String DocBaseType, ConnectionProvider conn) {
    BigDecimal m_Amt = ZERO;
    try {
        if (!Amt.equals(""))
            m_Amt = new BigDecimal(Amt);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    if (m_Amt.compareTo(ZERO) < 0)
        return createLine(docLine, accountCr, C_Currency_ID, "", m_Amt.abs().toString(), Fact_Acct_Group_ID,
                SeqNo, DocBaseType, conn);
    else
        return createLine(docLine, accountDr, C_Currency_ID, m_Amt.toString(), "", Fact_Acct_Group_ID, SeqNo,
                DocBaseType, conn);
}