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.amanzi.awe.statistics.ui.table.StatisticsLabelProvider.java

@Override
public String getColumnText(final Object element, int columnIndex) {
    if (columnIndex == 0) {
        return StringUtils.EMPTY;
    } else {/*ww  w .j  a v a 2 s . c o m*/
        columnIndex--;
    }

    if (element instanceof IStatisticsRow) {
        final IStatisticsRow statisticsRow = (IStatisticsRow) element;

        if (!statisticsRow.equals(previousRow)) {
            initializeCellList(statisticsRow);

            previousRow = statisticsRow;
        }

        switch (columnIndex) {
        case 0:
            return statisticsRow.getStatisticsGroup().getPropertyValue();
        case 1:
            return getStatisticsRowName(statisticsRow);
        default:
            final Number value = cellList.get(columnIndex - 2).getValue();
            if (value != null) {
                final float floatValue = value.floatValue();
                final BigDecimal bd = new BigDecimal(floatValue).setScale(DECIMAL_SIZE, RoundingMode.HALF_EVEN);
                return bd.toString();
            }
        }
    }

    return StringUtils.EMPTY;
}

From source file:org.osaf.cosmo.eim.eimml.EimmlTypeConverterTest.java

/** */
public void testToDecimal() throws Exception {
    try {/*from w  w w .jav  a  2 s  . c om*/
        EimmlTypeConverter.toDecimal("deadbeef");
        fail("converted to decimal with a bogus string");
    } catch (EimmlConversionException e) {
    }

    String testString = "3.14159";
    BigDecimal resultDecimal = EimmlTypeConverter.toDecimal(testString);

    assertEquals("Result decimal does not match", resultDecimal.toString(), testString);
}

From source file:com.iisigroup.cap.component.impl.AjaxFormResult.java

/**
 * ?// w ww. j a  v  a 2  s  .  c  o  m
 * 
 * @param key
 *            String
 * @param val
 *            Integer
 * @return this FormResult
 */
public AjaxFormResult set(String key, BigDecimal val) {
    resultMap.put(key, val.toString());
    return this;
}

From source file:com.wakacommerce.common.cache.StatisticsServiceImpl.java

@Override
public void addCacheStat(String key, boolean isHit) {
    CacheStat myStat = getCacheStat(key);
    if (isHit) {//from w ww  .  j  a va  2s . c  o m
        myStat.incrementHit();
    }
    myStat.incrementRequest();
    if (myStat.getLastLogTime() + logResolution < SystemTime.asMillis()) {
        myStat.setLastLogTime(SystemTime.asMillis());
        BigDecimal percentage = myStat.getHitRate();
        if (LOG.isInfoEnabled()) {
            LOG.info("Cache hit percentage for " + key + " is: " + percentage.toString() + "%");
        }
    }
}

From source file:de.iteratec.iteraplan.model.xml.query.QPartXML.java

private String getUnlocalizedNumber(String localizedNumber, Locale locale) {
    BigDecimal number = BigDecimalConverter.parse(localizedNumber, locale);
    return number.toString();
}

From source file:cn.kavelcortex.bookpriceculculator.TotalPrice.java

@Override
public void receivePrice(BigDecimal price, boolean b) {
    Log.d("receivePrice", "price:" + (b ? "add" : "subtract") + price.toString());
    if (b)/*from  w w w  .j  av  a  2 s.  co m*/
        totalPrice = totalPrice.add(price);
    else
        totalPrice = totalPrice.subtract(price);
    Log.d("receivePrice", "totalPrice:" + totalPrice.toString());
}

From source file:org.kuali.kpme.tklm.leave.calendar.validation.LeaveCalendarValidationUtil.java

public static List<String> validateAvailableLeaveBalanceForUsage(String earnCode, String leaveStartDateString,
        String leaveEndDateString, BigDecimal leaveAmount, LeaveBlock updatedLeaveBlock) {
    List<String> errors = new ArrayList<String>();
    boolean earnCodeChanged = false;
    BigDecimal oldAmount = null;/*w w w. j a v  a2  s  .c om*/

    if (leaveAmount == null) {
        leaveAmount = TKUtils.getHoursBetween(TKUtils.formatDateString(leaveStartDateString).toDate().getTime(),
                TKUtils.formatDateString(leaveEndDateString).toDate().getTime());
    }
    if (updatedLeaveBlock != null) {
        if (!updatedLeaveBlock.getEarnCode().equals(earnCode)) {
            earnCodeChanged = true;
        }
        if (!updatedLeaveBlock.getLeaveAmount().equals(leaveAmount)) {
            oldAmount = updatedLeaveBlock.getLeaveAmount();
        }
    }
    LocalDate startDate = TKUtils.formatDateString(leaveStartDateString);
    LocalDate endDate = TKUtils.formatDateString(leaveEndDateString);
    long daysSpan = TKUtils.getDaysBetween(startDate, endDate);
    EarnCodeContract earnCodeObj = HrServiceLocator.getEarnCodeService().getEarnCode(earnCode, endDate);
    if (earnCodeObj != null && earnCodeObj.getAllowNegativeAccrualBalance().equals("N")) {
        AccrualCategoryContract accrualCategory = HrServiceLocator.getAccrualCategoryService()
                .getAccrualCategory(earnCodeObj.getAccrualCategory(), endDate);
        if (accrualCategory != null) {
            AccrualEarnInterval accrualEarnInterval = AccrualEarnInterval
                    .fromCode(accrualCategory.getAccrualEarnInterval());
            DateTime nextIntervalDate;
            if (accrualEarnInterval != null && AccrualEarnInterval.PAY_CAL.equals(accrualEarnInterval)) {
                RateRangeAggregateContract rrAggregate = LmServiceLocator.getAccrualService()
                        .buildRateRangeAggregate(HrContext.getTargetPrincipalId(),
                                startDate.toDateTimeAtStartOfDay(), endDate.toDateTimeAtStartOfDay());
                PrincipalHRAttributesContract phra = rrAggregate.getRateOnDate(endDate.toDateTimeAtStartOfDay())
                        .getPrincipalHRAttributes();
                nextIntervalDate = LmServiceLocator.getAccrualService().getNextIntervalDate(
                        endDate.toDateTimeAtStartOfDay(), accrualEarnInterval.getCode(), phra.getPayCalendar(),
                        rrAggregate.getCalEntryMap());
            } else {
                nextIntervalDate = LmServiceLocator.getAccrualService().getNextAccrualIntervalDate(
                        accrualCategory.getAccrualEarnInterval(), endDate.toDateTimeAtStartOfDay());
            }
            // get the usage checking cut off Date, normally it's the day before the next interval date
            DateTime usageEndDate = nextIntervalDate;
            if (nextIntervalDate.compareTo(endDate.toDateTimeAtCurrentTime()) > 0) {
                usageEndDate = nextIntervalDate.minusDays(1);
            }
            // use the end of the year as the interval date for usage checking of no-accrual hours,
            // normally no-accrual hours are from banked/transferred system scheduled time offs
            if (accrualCategory.getAccrualEarnInterval().equals(AccrualEarnInterval.NO_ACCRUAL.getCode())) {
                usageEndDate = endDate.toDateTimeAtStartOfDay().withMonthOfYear(DateTimeConstants.DECEMBER)
                        .withDayOfMonth(31);
            }
            BigDecimal availableBalance = LmServiceLocator.getLeaveSummaryService()
                    .getLeaveBalanceForAccrCatUpToDate(HrContext.getTargetPrincipalId(), startDate, endDate,
                            accrualCategory.getAccrualCategory(), usageEndDate.toLocalDate());

            if (oldAmount != null) {
                if (!earnCodeChanged || (updatedLeaveBlock.getAccrualCategory() != null && updatedLeaveBlock
                        .getAccrualCategory().equals(accrualCategory.getAccrualCategory()))) {
                    availableBalance = availableBalance.add(oldAmount.abs());
                }
            }
            //multiply by days in span in case the user has also edited the start/end dates.
            // daySpan for the same start/end dates is 0 so we need to add 1 to it
            BigDecimal desiredUsage = leaveAmount.multiply(new BigDecimal(daysSpan + 1));
            //            BigDecimal desiredUsage =null;
            //            if(!HrConstants.EARN_CODE_TIME.equals(earnCodeObj.getRecordMethod())) {
            //               desiredUsage = leaveAmount.multiply(new BigDecimal(daysSpan+1));
            //            } else {
            //               desiredUsage = leaveAmount.multiply(new BigDecimal(daysSpan));
            //            }

            if (desiredUsage.compareTo(availableBalance) > 0) {
                errors.add("Requested leave amount " + desiredUsage.toString()
                        + " is greater than available leave balance " + availableBalance.toString()); //errorMessages
            }
        }
    }

    return errors;
}

From source file:py.una.pol.karaku.test.test.math.QuantityTest.java

private void assertQuantity(Quantity actual, BigDecimal bd) {

    int result = bd.compareTo(actual.bigDecimalValue());
    if (result != 0) {
        throw new ComparisonFailure("", actual.toString(), bd.toString());
    }//w  ww .  ja  va2  s. co  m
}

From source file:org.yes.cart.web.page.component.price.PriceView.java

@Override
protected void onBeforeRender() {

    boolean showSave = false;
    String savePercent = "";

    BigDecimal priceToFormat = pricePair.getFirst();
    String cssModificator = "regular";
    if (pricePair.getSecond() != null
            && MoneyUtils.isFirstBiggerThanSecond(pricePair.getFirst(), pricePair.getSecond())) {
        priceToFormat = pricePair.getSecond();
        cssModificator = "sale";
        showSave = this.showSavings;
        if (showSave) {
            final BigDecimal save = MoneyUtils.getDiscountDisplayValue(pricePair.getFirst(),
                    pricePair.getSecond());
            savePercent = save.toString();
        }//  w  w  w .  j a  v  a 2 s .c om
    }
    final String[] formatted = getFormattedPrice(priceToFormat);

    addOrReplace(new Label(WHOLE_LABEL, formatted[0])
            .add(new AttributeModifier(HTML_CLASS, cssModificator + CSS_SUFFIX_WHOLE)));
    addOrReplace(new Label(DOT_LABEL, ".")
            .setVisible(StringUtils.isNotBlank(formatted[0]) || StringUtils.isNotBlank(formatted[1]))
            .add(new AttributeModifier(HTML_CLASS, cssModificator + CSS_SUFFIX_DOT)));
    addOrReplace(new Label(DECIMAL_LABEL, formatted[1])
            .setVisible(StringUtils.isNotBlank(formatted[0]) || StringUtils.isNotBlank(formatted[1]))
            .add(new AttributeModifier(HTML_CLASS, cssModificator + CSS_SUFFIX_DECIMAL)));

    final Pair<String, Boolean> symbol = currencySymbolService.getCurrencySymbol(currencySymbol);

    addOrReplace(new Label(CURRENCY_LABEL, symbol.getFirst())
            .setVisible(showCurrencySymbol && !symbol.getSecond()).setEscapeModelStrings(false)
            .add(new AttributeModifier(HTML_CLASS, cssModificator + CSS_SUFFIX_CURRENCY)));

    addOrReplace(new Label(CURRENCY2_LABEL, symbol.getFirst())
            .setVisible(showCurrencySymbol && symbol.getSecond()).setEscapeModelStrings(false)
            .add(new AttributeModifier(HTML_CLASS, cssModificator + CSS_SUFFIX_CURRENCY)));

    addOrReplace(new Label(SAVE_LABEL,
            WicketUtil.createStringResourceModel(this, "savePercent",
                    Collections.<String, Object>singletonMap("discount", savePercent))).setVisible(showSave)
                            .add(new AttributeModifier(HTML_CLASS, "sale-price-save")));

    addOrReplace(new Label(PROMO_LABEL, promos).setVisible(StringUtils.isNotBlank(promos))
            .add(new AttributeModifier(HTML_CLASS, "sale-price-save")));

    super.onBeforeRender();

}

From source file:net.sourceforge.msscodefactory.cflib.v1_11.CFLib.Swing.CFJDoubleEditor.java

public boolean isEditValid() {
    final String S_ProcName = "isEditValid";
    if (!hasValue()) {
        setValue(null);// w  w w . j a  v a2  s .  com
        return (true);
    }

    boolean retval = super.isEditValid();
    if (retval) {
        try {
            commitEdit();
        } catch (ParseException e) {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "Field is not valid - " + e.getMessage(), e);

        }
        Object obj = getValue();
        if (obj == null) {
            retval = false;
        } else if (obj instanceof Float) {
            Float f = (Float) obj;
            Double v = new Double(f.doubleValue());
            if ((v.compareTo(minValue) < 0) || (v.compareTo(maxValue) > 0)) {
                retval = false;
            }
        } else if (obj instanceof Double) {
            Double v = (Double) obj;
            if ((v.compareTo(minValue) < 0) || (v.compareTo(maxValue) > 0)) {
                retval = false;
            }
        } else if (obj instanceof Short) {
            Short s = (Short) obj;
            Double v = new Double(s.doubleValue());
            if ((v.compareTo(minValue) < 0) || (v.compareTo(maxValue) > 0)) {
                retval = false;
            }
        } else if (obj instanceof Integer) {
            Integer i = (Integer) obj;
            Double v = new Double(i.doubleValue());
            if ((v.compareTo(minValue) < 0) || (v.compareTo(maxValue) > 0)) {
                retval = false;
            }
        } else if (obj instanceof Long) {
            Long l = (Long) obj;
            Double v = new Double(l.doubleValue());
            if ((v.compareTo(minValue) < 0) || (v.compareTo(maxValue) > 0)) {
                retval = false;
            }
        } else if (obj instanceof BigDecimal) {
            BigDecimal b = (BigDecimal) obj;
            Double v = new Double(b.toString());
            if ((v.compareTo(minValue) < 0) || (v.compareTo(maxValue) > 0)) {
                retval = false;
            }
        } else if (obj instanceof Number) {
            Number n = (Number) obj;
            Double v = new Double(n.toString());
            if ((v.compareTo(minValue) < 0) || (v.compareTo(maxValue) > 0)) {
                retval = false;
            }
        } else {
            throw CFLib.getDefaultExceptionFactory().newUnsupportedClassException(getClass(), S_ProcName,
                    "EditedValue", obj, "Short, Integer, Long, BigDecimal, Float, Double or Number");
        }
    }
    return (retval);
}