Example usage for java.math BigDecimal divide

List of usage examples for java.math BigDecimal divide

Introduction

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

Prototype

public BigDecimal divide(BigDecimal divisor) 

Source Link

Document

Returns a BigDecimal whose value is (this / divisor) , and whose preferred scale is (this.scale() - divisor.scale()) ; if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown.

Usage

From source file:org.hibernate.shards.strategy.exit.ShardedAvgExitOperation.java

public List<Object> apply(List<Object> results) {
    BigDecimal value = new BigDecimal(0.0);
    BigDecimal count = new BigDecimal(0.0);
    @SuppressWarnings("unchecked")
    List<Pair<Double, Integer>> pairList = (List<Pair<Double, Integer>>) (List) results;
    for (Pair<Double, Integer> pair : pairList) {
        // we know the order of the pair (avg, count) by convention of ShardedAvgProjection
        value = value.add(new BigDecimal(pair.first));
        count = count.add(new BigDecimal(pair.second));
    }//from www. j a  v  a  2  s  .c om
    return Lists.newArrayList((Object) value.divide(count));
}

From source file:org.apache.hadoop.hive.ql.optimizer.calcite.translator.ExprNodeConverter.java

/**
 * TODO: 1. Handle NULL/*from   www. j  a va  2 s .com*/
 */
@Override
public ExprNodeDesc visitLiteral(RexLiteral literal) {
    RelDataType lType = literal.getType();

    switch (literal.getType().getSqlTypeName()) {
    case BOOLEAN:
        return new ExprNodeConstantDesc(TypeInfoFactory.booleanTypeInfo,
                Boolean.valueOf(RexLiteral.booleanValue(literal)));
    case TINYINT:
        return new ExprNodeConstantDesc(TypeInfoFactory.byteTypeInfo,
                Byte.valueOf(((Number) literal.getValue3()).byteValue()));
    case SMALLINT:
        return new ExprNodeConstantDesc(TypeInfoFactory.shortTypeInfo,
                Short.valueOf(((Number) literal.getValue3()).shortValue()));
    case INTEGER:
        return new ExprNodeConstantDesc(TypeInfoFactory.intTypeInfo,
                Integer.valueOf(((Number) literal.getValue3()).intValue()));
    case BIGINT:
        return new ExprNodeConstantDesc(TypeInfoFactory.longTypeInfo,
                Long.valueOf(((Number) literal.getValue3()).longValue()));
    case FLOAT:
    case REAL:
        return new ExprNodeConstantDesc(TypeInfoFactory.floatTypeInfo,
                Float.valueOf(((Number) literal.getValue3()).floatValue()));
    case DOUBLE:
        return new ExprNodeConstantDesc(TypeInfoFactory.doubleTypeInfo,
                Double.valueOf(((Number) literal.getValue3()).doubleValue()));
    case DATE:
        return new ExprNodeConstantDesc(TypeInfoFactory.dateTypeInfo,
                new Date(((Calendar) literal.getValue()).getTimeInMillis()));
    case TIME:
    case TIMESTAMP: {
        Object value = literal.getValue3();
        if (value instanceof Long) {
            value = new Timestamp((Long) value);
        }
        return new ExprNodeConstantDesc(TypeInfoFactory.timestampTypeInfo, value);
    }
    case BINARY:
        return new ExprNodeConstantDesc(TypeInfoFactory.binaryTypeInfo, literal.getValue3());
    case DECIMAL:
        return new ExprNodeConstantDesc(
                TypeInfoFactory.getDecimalTypeInfo(lType.getPrecision(), lType.getScale()),
                literal.getValue3());
    case VARCHAR: {
        int varcharLength = lType.getPrecision();
        // If we cannot use Varchar due to type length restrictions, we use String
        if (varcharLength < 1 || varcharLength > HiveVarchar.MAX_VARCHAR_LENGTH) {
            return new ExprNodeConstantDesc(TypeInfoFactory.stringTypeInfo, literal.getValue3());
        }
        return new ExprNodeConstantDesc(TypeInfoFactory.getVarcharTypeInfo(varcharLength),
                new HiveVarchar((String) literal.getValue3(), varcharLength));
    }
    case CHAR: {
        int charLength = lType.getPrecision();
        // If we cannot use Char due to type length restrictions, we use String
        if (charLength < 1 || charLength > HiveChar.MAX_CHAR_LENGTH) {
            return new ExprNodeConstantDesc(TypeInfoFactory.stringTypeInfo, literal.getValue3());
        }
        return new ExprNodeConstantDesc(TypeInfoFactory.getCharTypeInfo(charLength),
                new HiveChar((String) literal.getValue3(), charLength));
    }
    case INTERVAL_YEAR_MONTH: {
        BigDecimal monthsBd = (BigDecimal) literal.getValue();
        return new ExprNodeConstantDesc(TypeInfoFactory.intervalYearMonthTypeInfo,
                new HiveIntervalYearMonth(monthsBd.intValue()));
    }
    case INTERVAL_DAY_TIME: {
        BigDecimal millisBd = (BigDecimal) literal.getValue();
        // Calcite literal is in millis, we need to convert to seconds
        BigDecimal secsBd = millisBd.divide(BigDecimal.valueOf(1000));
        return new ExprNodeConstantDesc(TypeInfoFactory.intervalDayTimeTypeInfo,
                new HiveIntervalDayTime(secsBd));
    }
    case OTHER:
    default:
        return new ExprNodeConstantDesc(TypeInfoFactory.voidTypeInfo, literal.getValue3());
    }
}

From source file:org.openhab.binding.wemo.internal.WemoBinding.java

/**
 * @{inheritDoc}//from  w w  w.  ja v a 2 s . c  om
 */
@Override
protected void execute() {
    logger.debug("execute() method is called!");

    for (WemoBindingProvider provider : providers) {
        for (String itemName : provider.getItemNames()) {
            logger.debug("Wemo item '{}' state will be updated", itemName);

            try {
                if (provider.getUDN(itemName).toLowerCase().contains("insight")) {
                    String insightParams = getInsightParams(itemName);

                    if (insightParams != null) {

                        String[] splitInsightParams = insightParams.split("\\|");

                        if (splitInsightParams[0] != null) {

                            if (provider.getChannelType(itemName).equals(WemoChannelType.state)) {
                                OnOffType binaryState = null;
                                binaryState = splitInsightParams[0].equals("0") ? OnOffType.OFF : OnOffType.ON;
                                if (binaryState != null) {
                                    logger.trace("New InsightParam binaryState '{}' for device '{}' received",
                                            binaryState, itemName);
                                    eventPublisher.postUpdate(itemName, binaryState);
                                }
                            }

                            if (provider.getChannelType(itemName).equals(WemoChannelType.lastOnFor)) {
                                State lastOnFor = DecimalType.valueOf(splitInsightParams[2]);
                                if (lastOnFor != null) {
                                    logger.trace("New InsightParam lastOnFor '{}' for device '{}' received",
                                            lastOnFor, itemName);
                                    eventPublisher.postUpdate(itemName, lastOnFor);
                                }
                            }

                            if (provider.getChannelType(itemName).equals(WemoChannelType.onToday)) {
                                State onToday = DecimalType.valueOf(splitInsightParams[3]);
                                if (onToday != null) {
                                    logger.trace("New InsightParam lastOnFor '{}' for device '{}' received",
                                            onToday, itemName);
                                    eventPublisher.postUpdate(itemName, onToday);
                                }
                            }

                            if (provider.getChannelType(itemName).equals(WemoChannelType.onTotal)) {
                                State onTotal = DecimalType.valueOf(splitInsightParams[4]);
                                if (onTotal != null) {
                                    logger.trace("New InsightParam lastOnFor '{}' for device '{}' received",
                                            onTotal, itemName);
                                    eventPublisher.postUpdate(itemName, onTotal);
                                }
                            }

                            if (provider.getChannelType(itemName).equals(WemoChannelType.currentPower)) {
                                BigDecimal currentMW = new BigDecimal(splitInsightParams[7]);
                                State currentPower = new DecimalType(currentMW.divide(new BigDecimal(1000))); // recalculate
                                                                                                              // mW to W
                                if (currentPower != null) {
                                    logger.trace("New InsightParam lastOnFor '{}' for device '{}' received",
                                            currentPower, itemName);
                                    eventPublisher.postUpdate(itemName, currentPower);
                                }
                            }
                        }
                    }

                } else {
                    String state = getWemoState(itemName);

                    if (state != null) {
                        if (provider.getUDN(itemName).toLowerCase().contains("motion")) {
                            State newState = state.equals("0") ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
                            eventPublisher.postUpdate(itemName, newState);
                        } else {
                            State itemState = state.equals("0") ? OnOffType.OFF : OnOffType.ON;
                            eventPublisher.postUpdate(itemName, itemState);

                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}

From source file:org.openhab.binding.denon.internal.DenonConnector.java

private String toDenonValue(BigDecimal percent) {
    // Round to nearest number divisible by 0.5 
    percent = percent.divide(POINTFIVE).setScale(0, RoundingMode.UP).multiply(POINTFIVE)
            .min(connection.getMainVolumeMax()).max(BigDecimal.ZERO);

    String dbString = String.valueOf(percent.intValue());

    if (percent.compareTo(BigDecimal.TEN) == -1) {
        dbString = "0" + dbString;
    }/*from www.j  a  v  a 2s  .c o  m*/
    if (percent.remainder(BigDecimal.ONE).equals(POINTFIVE)) {
        dbString = dbString + "5";
    }

    return dbString;
}

From source file:com.siapa.managedbean.DetalleMuestreoManagedBean.java

@Override
public void saveNew(ActionEvent event) {
    DetalleMuestreo detallemuestreo = getDetallemuestreo();
    detallemuestreo.setIdMuestreo(muestreo);
    detallemuestreoService.save(detallemuestreo);
    BigInteger cant = detallemuestreoService.cantidad(muestreo.getIdMuestreo());

    BigDecimal dividir = new BigDecimal(cant);
    List<DetalleMuestreo> q = detallemuestreoService.findAll();
    BigDecimal suma = BigDecimal.ZERO;
    BigDecimal promedio = BigDecimal.ZERO;

    for (DetalleMuestreo detalle : q) {
        if (detalle.getIdMuestreo().getIdMuestreo() == muestreo.getIdMuestreo()) {
            suma = suma.add(detalle.getPesoDetalleMuestreo());
        }//from  w w w. java 2  s .  c  o  m
    }
    int sumaint = suma.intValue();
    int cantint = cant.intValue();
    //int prom=sumaint/cantint;
    //  promedio=new BigDecimal(prom);
    //  System.out.println(prom);
    promedio = suma.divide(dividir);
    Muestreo newMuestreo = getMuestreo();
    newMuestreo.setPesoPromedioMuestreo(suma.divide(dividir));
    //  muestreo.setPesoPromedioMuestreo(suma);
    System.out.println(promedio);
    muestreoService.merge(newMuestreo);

    loadLazyModels();
    FacesContext context = FacesContext.getCurrentInstance();
    context.addMessage(null, new FacesMessage("Successful"));
    try {
        FacesContext context1 = FacesContext.getCurrentInstance();
        context1.getExternalContext().redirect("/siapa/views/detalleMuestreo/index.xhtml");
    } catch (IOException e) {

    }

}

From source file:org.jboss.tools.project.examples.model.ProjectExample.java

public String getSizeAsText() {
    String sizeString = ""; //$NON-NLS-1$
    BigDecimal sizeDecimal = new BigDecimal(size);
    BigDecimal MB = new BigDecimal(1024 * 1024);
    BigDecimal KB = new BigDecimal(1024);
    if (sizeDecimal.compareTo(MB) > 0) {
        sizeString = String.format(Locale.US, "%5.2fMB", sizeDecimal.divide(MB)); //$NON-NLS-1$
    } else if (sizeDecimal.compareTo(KB) > 0) {
        sizeString = String.format(Locale.US, "%5.2fKB", sizeDecimal.divide(KB)); //$NON-NLS-1$
    } else {/*from w w w.  j  a  v a 2  s.com*/
        sizeString = String.format("%db", size); //$NON-NLS-1$
    }
    return sizeString;
}

From source file:org.openhab.binding.denon.internal.DenonConnector.java

private BigDecimal fromDenonValue(String string) {
    /*//from w w w  . j a va2 s. co m
     * 455 = 45,5
     * 45 = 45
     * 045 = 4,5
     * 04 = 4 
     */
    BigDecimal value = new BigDecimal(string);
    if (value.compareTo(NINETYNINE) == 1 || (string.startsWith("0") && string.length() > 2)) {
        value = value.divide(BigDecimal.TEN);
    }

    return value;
}

From source file:nz.Intelx.DroidNetLogin.DroidNetLoginActivity.java

private void updateUI() {

    LoginFragment Login_Fragment = (LoginFragment) getSupportFragmentManager()
            .findFragmentByTag("android:switcher:" + R.id.pager + ":0");

    if (Login_Fragment != null && Login_Fragment.getView() != null) {
        TextView t = (TextView) Login_Fragment.getActivity().findViewById(R.id.Status);
        TextView t2 = (TextView) Login_Fragment.getActivity().findViewById(R.id.Usage);
        TextView t3 = (TextView) Login_Fragment.getActivity().findViewById(R.id.proxy_status);
        ToggleButton b = (ToggleButton) Login_Fragment.getActivity().findViewById(R.id.Auto);

        Status = preferences.getInt("Status", -1);
        Proxy = preferences.getBoolean("Proxy", false);
        IP_Usage = preferences.getInt("IP_Usage", 0);

        switch (Status) {
        case 1://www  .  ja v  a 2  s.c  o  m
            t.setText("Status: Logging in");
            break;
        case 2:
            t.setText("Status: Connected!");
            break;
        case 3:
            t.setText("Status: Disconnected");
            break;
        case 4:
            t.setText("Status: Error");
            break;
        }

        BigDecimal Usage = new BigDecimal(IP_Usage);

        t2.setText("Usage: " + Usage.divide(new BigDecimal(1000)) + " MB");

        if (Proxy) {
            t3.setText("Proxy: Started");
        } else {
            t3.setText("Proxy: Stopped");
        }

        if (Proxy_Option) {
            if (Status == 2 && Proxy == true) {
                b.setChecked(true);
            } else {
                b.setChecked(false);
            }
        } else {
            if (Status == 2) {
                b.setChecked(true);
            } else {
                b.setChecked(false);
            }
        }

    }
}