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:pe.gob.mef.gescon.hibernate.impl.UserDaoImpl.java

@Override
@Transactional(readOnly = false)/*from w w  w.j a v a  2  s.co  m*/
public void deletePerfilByUser(final BigDecimal idusuario) throws Exception {
    getHibernateTemplate().execute(new HibernateCallback() {
        @Override
        public Object doInHibernate(Session session) throws HibernateException {
            StringBuilder sql = new StringBuilder();
            sql.append("DELETE FROM TUSER_PERFIL WHERE NUSUARIOID = ");
            sql.append(idusuario.toString());
            Query query = session.createSQLQuery(sql.toString());
            return query.executeUpdate();
        }
    });
}

From source file:org.apache.hadoop.mapreduce.lib.db.BigDecimalSplitter.java

public List<InputSplit> split(Configuration conf, ResultSet results, String colName) throws SQLException {

    BigDecimal minVal = results.getBigDecimal(1);
    BigDecimal maxVal = results.getBigDecimal(2);

    String lowClausePrefix = colName + " >= ";
    String highClausePrefix = colName + " < ";

    BigDecimal numSplits = new BigDecimal(conf.getInt("mapred.map.tasks", 1));

    if (minVal == null && maxVal == null) {
        // Range is null to null. Return a null split accordingly.
        List<InputSplit> splits = new ArrayList<InputSplit>();
        splits.add(//from w  w  w.  j  a va 2 s . c  o  m
                new DataDrivenDBInputFormat.DataDrivenDBInputSplit(colName + " IS NULL", colName + " IS NULL"));
        return splits;
    }

    if (minVal == null || maxVal == null) {
        // Don't know what is a reasonable min/max value for interpolation. Fail.
        LOG.error("Cannot find a range for NUMERIC or DECIMAL fields with one end NULL.");
        return null;
    }

    // Get all the split points together.
    List<BigDecimal> splitPoints = split(numSplits, minVal, maxVal);
    List<InputSplit> splits = new ArrayList<InputSplit>();

    // Turn the split points into a set of intervals.
    BigDecimal start = splitPoints.get(0);
    for (int i = 1; i < splitPoints.size(); i++) {
        BigDecimal end = splitPoints.get(i);

        if (i == splitPoints.size() - 1) {
            // This is the last one; use a closed interval.
            splits.add(new DataDrivenDBInputFormat.DataDrivenDBInputSplit(lowClausePrefix + start.toString(),
                    colName + " <= " + end.toString()));
        } else {
            // Normal open-interval case.
            splits.add(new DataDrivenDBInputFormat.DataDrivenDBInputSplit(lowClausePrefix + start.toString(),
                    highClausePrefix + end.toString()));
        }

        start = end;
    }

    return splits;
}

From source file:org.openhab.ui.basic.internal.render.SetpointRenderer.java

@Override
public EList<Widget> renderWidget(Widget w, StringBuilder sb) throws RenderException {
    Setpoint sp = (Setpoint) w;//w ww.j av a2  s.co m

    State state = itemUIRegistry.getState(w);
    String newLowerState = state.toString();
    String newHigherState = state.toString();

    // set defaults for min, max and step
    BigDecimal step = sp.getStep();
    if (step == null) {
        step = BigDecimal.ONE;
    }
    BigDecimal minValue = sp.getMinValue();
    if (minValue == null) {
        minValue = BigDecimal.ZERO;
    }
    BigDecimal maxValue = sp.getMaxValue();
    if (maxValue == null) {
        maxValue = BigDecimal.valueOf(100);
    }

    // if the current state is a valid value, we calculate the up and down step values
    if (state instanceof DecimalType) {
        DecimalType actState = (DecimalType) state;
        BigDecimal newLower = actState.toBigDecimal().subtract(step);
        BigDecimal newHigher = actState.toBigDecimal().add(step);
        if (newLower.compareTo(minValue) < 0) {
            newLower = minValue;
        }
        if (newHigher.compareTo(maxValue) > 0) {
            newHigher = maxValue;
        }
        newLowerState = newLower.toString();
        newHigherState = newHigher.toString();
    }

    String unit = getUnitForWidget(w);

    String snippetName = "setpoint";
    String snippet = getSnippet(snippetName);

    snippet = preprocessSnippet(snippet, w);
    snippet = StringUtils.replace(snippet, "%newlowerstate%", newLowerState);
    snippet = StringUtils.replace(snippet, "%newhigherstate%", newHigherState);
    snippet = StringUtils.replace(snippet, "%value%", getValue(w));
    snippet = StringUtils.replace(snippet, "%minValue%", minValue.toString());
    snippet = StringUtils.replace(snippet, "%maxValue%", maxValue.toString());
    snippet = StringUtils.replace(snippet, "%step%", step.toString());
    snippet = StringUtils.replace(snippet, "%unit%", unit);

    // Process the color tags
    snippet = processColor(w, snippet);

    sb.append(snippet);
    return null;
}

From source file:be.error.rpi.heating.HeatingController.java

private void process(RoomTemperature sorted, RoomTemperature previous) throws Exception {
    //Whenever we switch room, the heating controller needs to be 'reset' to reflect the current heating demand of that room
    if (previous.getRoomId() != sorted.getRoomId()) {
        logger.debug("Sending RESET desired temp " + sorted.getDesiredTemp().toString() + " to ebusd for room "
                + sorted.getRoomId());/*w  ww.  j  a  va 2  s .com*/
        new EbusdTcpCommunicatorImpl(ebusDeviceAddress)
                .send(new SetDesiredRoomTemperature(sorted.getDesiredTemp(), ebusDeviceAddress));

        BigDecimal resetControlTemp = controlValueCalculator.getResetControlValue(sorted.getHeatingDemand(),
                sorted.getDesiredTemp());
        logger.debug("Sending RESET current temp " + sorted.getCurrentTemp().toString() + " (control temp:"
                + resetControlTemp.toString() + ") to ebusd for room " + sorted.getRoomId());
        new EbusdTcpCommunicatorImpl(ebusDeviceAddress)
                .send(new SetCurrentRoomTemperature(resetControlTemp, sorted.getCurrentTemp()));
    }

    BigDecimal currentTemp = sorted.getCurrentTemp();
    BigDecimal desiredTemp = sorted.getDesiredTemp();

    logger.debug("Sending desired temp " + desiredTemp.toString() + " to ebusd for room " + sorted.getRoomId());
    new EbusdTcpCommunicatorImpl(ebusDeviceAddress)
            .send(new SetDesiredRoomTemperature(desiredTemp, ebusDeviceAddress));

    BigDecimal controlTemp = controlValueCalculator.getControlValue(currentTemp, desiredTemp);
    logger.debug("Sending current temp " + currentTemp.toString() + "(control temp:" + controlTemp.toString()
            + " to ebusd for room " + sorted.getRoomId());
    new EbusdTcpCommunicatorImpl(ebusDeviceAddress)
            .send(new SetCurrentRoomTemperature(controlTemp, currentTemp));

    lastSendRoomTemperature = of(sorted);

    logger.debug("Scheduling job for obtaining HC status");
    heatingInfoPollerJobSchedulerFactory.triggerNow();
}

From source file:io.coala.config.AbstractPropertyGetter.java

/**
 * @param defaultValue//from  w  w  w. j a v a  2 s  .  c o m
 * @return
 */
public BigDecimal getBigDecimal(final BigDecimal defaultValue) {
    return new BigDecimal(get(defaultValue.toString()));
}

From source file:org.kuali.kpme.tklm.leave.payout.validation.LeavePayoutValidationUtils.java

private static boolean validatePayoutAmount(BigDecimal payoutAmount, AccrualCategory fromCat, EarnCode earnCode,
        String principalId, LocalDate effectiveDate, AccrualCategoryRule accrualRule) {

    LeaveSummaryContract leaveSummary = LmServiceLocator.getLeaveSummaryService()
            .getLeaveSummaryAsOfDateForAccrualCategory(principalId, effectiveDate,
                    fromCat.getAccrualCategory());
    LeaveSummaryRowContract row = leaveSummary.getLeaveSummaryRowForAccrualCtgy(fromCat.getAccrualCategory());
    BigDecimal balance = row.getAccruedBalance();
    //transfer amount must be less than the max transfer amount defined in the accrual category rule.
    //it cannot be negative.
    boolean isValid = true;

    BigDecimal maxPayoutAmount = null;
    BigDecimal adjustedMaxPayoutAmount = null;
    if (ObjectUtils.isNotNull(accrualRule.getMaxPayoutAmount())) {
        maxPayoutAmount = new BigDecimal(accrualRule.getMaxPayoutAmount());
        BigDecimal fullTimeEngagement = HrServiceLocator.getJobService()
                .getFteSumForAllActiveLeaveEligibleJobs(principalId, effectiveDate);
        adjustedMaxPayoutAmount = maxPayoutAmount.multiply(fullTimeEngagement);
    }//from   w  ww  .  j a v a 2 s. c  o m

    //use override if one exists.
    EmployeeOverrideContract maxPayoutAmountOverride = LmServiceLocator.getEmployeeOverrideService()
            .getEmployeeOverride(principalId, fromCat.getLeavePlan(), fromCat.getAccrualCategory(), "MPA",
                    effectiveDate);
    if (ObjectUtils.isNotNull(maxPayoutAmountOverride))
        adjustedMaxPayoutAmount = new BigDecimal(maxPayoutAmountOverride.getOverrideValue());

    if (ObjectUtils.isNotNull(adjustedMaxPayoutAmount)) {
        if (payoutAmount.compareTo(adjustedMaxPayoutAmount) > 0) {
            isValid &= false;
            String fromUnitOfTime = HrConstants.UNIT_OF_TIME.get(fromCat.getUnitOfTime());
            GlobalVariables.getMessageMap().putError("leavePayout.payoutAmount",
                    "leavePayout.payoutAmount.maxPayoutAmount", adjustedMaxPayoutAmount.toString(),
                    fromUnitOfTime);
        }
    }
    // check for a positive amount.
    if (payoutAmount.compareTo(BigDecimal.ZERO) < 0) {
        isValid &= false;
        GlobalVariables.getMessageMap().putError("leavePayout.payoutAmount",
                "leavePayout.payoutAmount.negative");
    }

    if (payoutAmount.compareTo(balance) > 0) {
        isValid &= false;
        GlobalVariables.getMessageMap().putError("leavePayout.payoutAmount", "maxBalance.amount.exceedsBalance",
                balance.toString());
    }
    return isValid;
}

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

public static String formatUInt64(BigDecimal val) {
    final String S_ProcName = "formatUInt64";
    if (val == null) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(CFLibXmlUtil.class, S_ProcName, 1,
                "val");
    }//from w  ww .j  a  va 2 s. c  o  m
    String retval = val.toString();
    return (retval);
}

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

public static String formatNumber(BigDecimal val) {
    final String S_ProcName = "formatNumber";
    if (val == null) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(CFLibXmlUtil.class, S_ProcName, 1,
                "val");
    }//from w  ww.j ava  2 s. c om
    String retval = val.toString();
    return (retval);
}

From source file:org.kalypso.kalypsomodel1d2d.ui.map.flowrel.ChooseProfileFeatureControl.java

protected void showDialog(final Shell shell) {
    final Feature feature = getFeature();
    if (feature == null)
        return;/*from   ww  w.java 2s .  c o  m*/

    final IFlowRelationship flowRel = (IFlowRelationship) feature.getAdapter(IFlowRelationship.class);
    Assert.isNotNull(flowRel);

    final Feature realProfileFeature = getLinkedProfileFeature();

    try {
        // TODO: add filter depending on relation type (bridge, weir, normal)

        // find network
        final IScenarioDataProvider dataProvider = KalypsoAFGUIFrameworkPlugin.getDataProvider();
        final ITerrainModel terrainModel = dataProvider.getModel(ITerrainModel.class.getName());

        final GMLWorkspace root = terrainModel.getWorkspace();
        final GMLContentProvider cp = new GMLContentProvider(false, false);
        cp.setRootPath(new GMLXPath(terrainModel.getRiverProfileNetworkCollection()));
        final TreeSingleSelectionDialog treeSelectionDialog = new TreeSingleSelectionDialog(shell, root, cp,
                new GMLLabelProvider(), Messages.getString(
                        "org.kalypso.kalypsomodel1d2d.ui.map.flowrel.ChooseProfileFeatureControl.2")); //$NON-NLS-1$

        if (realProfileFeature != null)
            treeSelectionDialog.setInitialSelections(new Object[] { realProfileFeature });

        if (treeSelectionDialog.open() == Window.CANCEL)
            return;

        final Feature newProfileLink = (Feature) treeSelectionDialog.getResult()[0];
        if (!(newProfileLink instanceof IProfileFeature))
            return;

        // TODO: check, if the chosen profile is suitable for this relation
        final IProfile profile = ((IProfileFeature) newProfileLink).getProfile();

        final String profileRef = "terrain.gml#" + newProfileLink.getId(); //$NON-NLS-1$
        if (flowRel instanceof ITeschkeFlowRelation) {
            final Feature newLinkFeature = feature.setLink(ITeschkeFlowRelation.QNAME_PROP_PROFILE, profileRef);
            final IRelationType pt = (IRelationType) flowRel.getFeatureType()
                    .getProperty(ITeschkeFlowRelation.QNAME_PROP_PROFILE);
            fireFeatureChange(new ChangeFeatureCommand(flowRel, pt, newLinkFeature));
        } else if (flowRel instanceof IBuildingFlowRelation) {
            final IProfileObject[] profileObjects = profile.getProfileObjects(IProfileBuilding.class);
            if (ArrayUtils.isEmpty(profileObjects))
                MessageDialog.openWarning(shell,
                        Messages.getString(
                                "org.kalypso.kalypsomodel1d2d.ui.map.flowrel.ChooseProfileFeatureControl.9"), //$NON-NLS-1$
                        Messages.getString(
                                "org.kalypso.kalypsomodel1d2d.ui.map.flowrel.ChooseProfileFeatureControl.10")); //$NON-NLS-1$
            else {
                final IProfileObject building = profileObjects[0];

                if (flowRel instanceof IBridgeFlowRelation && !(building instanceof BuildingBruecke))
                    MessageDialog.openWarning(shell, Messages.getString(
                            "org.kalypso.kalypsomodel1d2d.ui.map.flowrel.ChooseProfileFeatureControl.11"), //$NON-NLS-1$
                            Messages.getString(
                                    "org.kalypso.kalypsomodel1d2d.ui.map.flowrel.ChooseProfileFeatureControl.12")); //$NON-NLS-1$
                else if (flowRel instanceof IWeirFlowRelation && !(building instanceof BuildingWehr))
                    MessageDialog.openWarning(shell, Messages.getString(
                            "org.kalypso.kalypsomodel1d2d.ui.map.flowrel.ChooseProfileFeatureControl.13"), //$NON-NLS-1$
                            Messages.getString(
                                    "org.kalypso.kalypsomodel1d2d.ui.map.flowrel.ChooseProfileFeatureControl.14")); //$NON-NLS-1$
                else {
                    final IRelationType pt = (IRelationType) flowRel.getFeatureType()
                            .getProperty(IBuildingFlowRelation.QNAME_PROP_PROFILE);
                    final Feature newLinkFeature = feature.setLink(pt, profileRef);
                    fireFeatureChange(new ChangeFeatureCommand(flowRel, pt, newLinkFeature));
                }
            }
        }
        // //TODO: check for 2d if it is needed
        // else if( flowRel instanceof IBuildingFlowRelation2D )
        // {
        // final IProfileObject[] profileObjects = profile.getProfileObjects();
        // if( profileObjects.length == 0 )
        //          MessageDialog.openWarning( shell, Messages.getString("org.kalypso.kalypsomodel1d2d.ui.map.flowrel.ChooseProfileFeatureControl.9"), Messages.getString("org.kalypso.kalypsomodel1d2d.ui.map.flowrel.ChooseProfileFeatureControl.10") ); //$NON-NLS-1$ //$NON-NLS-2$
        // else
        // {
        // final IRelationType pt = (IRelationType) flowRel.getFeatureType().getProperty(
        // IBuildingFlowRelation2D.QNAME_PROP_PROFILE );
        //          final Feature newLinkFeature = new XLinkedFeature_Impl( feature, pt, pt.getTargetFeatureType(), profileRef, "", "", "", "", "" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
        // fireFeatureChange( new ChangeFeatureCommand( flowRel, pt, newLinkFeature ) );
        // }
        // }

        // TODO: set name of flowrel according to profile or create a dummy name
        final double station = profile.getStation();
        final BigDecimal bigStation = ProfileUtil.stationToBigDecimal(station);

        if (StringUtils.isBlank(flowRel.getName()))
            flowRel.setName(bigStation.toString()); //$NON-NLS-1$

        // Automatically update station of TeschkeFlowRelation
        if (flowRel instanceof TeschkeFlowRelation)
            ((TeschkeFlowRelation) flowRel).setStation(bigStation);
    } catch (final CoreException e) {
        KalypsoModel1D2DPlugin.getDefault().getLog().log(e.getStatus());
        ErrorDialog.openError(shell,
                Messages.getString(
                        "org.kalypso.kalypsomodel1d2d.ui.map.flowrel.ChooseProfileFeatureControl.22"), //$NON-NLS-1$
                Messages.getString(
                        "org.kalypso.kalypsomodel1d2d.ui.map.flowrel.ChooseProfileFeatureControl.23"), //$NON-NLS-1$
                e.getStatus());
    } catch (final GMLXPathException e) {
        final IStatus status = StatusUtilities.statusFromThrowable(e);
        KalypsoModel1D2DPlugin.getDefault().getLog().log(status);
        ErrorDialog.openError(shell,
                Messages.getString(
                        "org.kalypso.kalypsomodel1d2d.ui.map.flowrel.ChooseProfileFeatureControl.24"), //$NON-NLS-1$
                Messages.getString(
                        "org.kalypso.kalypsomodel1d2d.ui.map.flowrel.ChooseProfileFeatureControl.25"), //$NON-NLS-1$
                status);
    }
}

From source file:org.kuali.kpme.pm.classification.validation.ClassificationValidation.java

private boolean validatePercentTime(ClassificationBo clss) {
    if (CollectionUtils.isNotEmpty(clss.getDutyList())) {
        BigDecimal sum = BigDecimal.ZERO;
        for (ClassificationDutyBo aDuty : clss.getDutyList()) {
            if (aDuty != null && aDuty.getPercentage() != null) {
                sum = sum.add(aDuty.getPercentage());
            }/*from   w  w w . jav a  2s. c o m*/
        }
        if (sum.compareTo(new BigDecimal(100)) > 0) {
            String[] parameters = new String[1];
            parameters[0] = sum.toString();

            this.putFieldError("dataObject.dutyList", "duty.percentage.exceedsMaximum", parameters);
            return false;
        }
    }
    return true;
}