Example usage for java.math BigDecimal multiply

List of usage examples for java.math BigDecimal multiply

Introduction

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

Prototype

public BigDecimal multiply(BigDecimal multiplicand) 

Source Link

Document

Returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()) .

Usage

From source file:de.csdev.ebus.command.EBusCommandUtils.java

/**
 * Apply all post number operations like multiply, range check etc.
 *
 * @param decode//from   w ww .java2s .c o m
 * @param ev
 * @return
 */
private static Object applyNumberOperations(Object decode, IEBusValue ev) {

    if (ev instanceof EBusCommandValue) {
        EBusCommandValue nev = (EBusCommandValue) ev;

        if (decode instanceof BigDecimal) {

            BigDecimal multiply = (BigDecimal) decode;

            if (nev.getFactor() != null) {
                multiply = multiply.multiply(nev.getFactor());
                decode = multiply;
            }

            if (nev.getMin() != null && multiply.compareTo(nev.getMin()) == -1) {
                logger.debug("Value {} with {} is smaller then allowed {}", ev.getName(), multiply,
                        nev.getMax());
                decode = null;
            }

            if (nev.getMax() != null && multiply.compareTo(nev.getMax()) == 1) {
                logger.debug("Value {} with {} is larger then allowed {}", ev.getName(), multiply,
                        nev.getMax());
                decode = null;
            }
        }
    }

    return decode;
}

From source file:com.intuit.tank.project.JobDetailFormatter.java

protected static BigDecimal estimateCost(int numInstances, BigDecimal costPerHour, long time) {
    BigDecimal cost = BigDecimal.ZERO;
    // calculate the number of machines and the expected run time
    BigDecimal hours = new BigDecimal(Math.max(1, Math.ceil(time / HOURS)));
    cost = cost.add(costPerHour.multiply(new BigDecimal(numInstances)).multiply(hours));
    // dynamoDB costs about 1.5 times the instance cost
    cost = cost.add(cost.multiply(new BigDecimal(1.5D)));
    return cost;/*from   w w w .j  av  a2s.co m*/
}

From source file:com.dopecoin.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, float leafBtcConversion,
        final String userAgent, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;//from w  w  w .  ja v  a2 s .c o m

    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                    Constants.UTF_8);
            final StringBuilder content = new StringBuilder();
            Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                BigDecimal btcRate = new BigDecimal(GenericUtils.toNanoCoins(rate, 0));
                                BigInteger leafRate = btcRate.multiply(BigDecimal.valueOf(leafBtcConversion))
                                        .toBigInteger();

                                if (leafRate.signum() > 0) {
                                    rates.put(currencyCode,
                                            new ExchangeRate(currencyCode, leafRate, url.getHost()));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {}: {}",
                                        new Object[] { currencyCode, url, x.getMessage() });
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {}, took {} ms", url, (System.currentTimeMillis() - start));

            return rates;
        } else {
            log.warn("http status {} when fetching {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:de.jdellay.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, float ccnBtcConversion,
        final String userAgent, final String source, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;//from   w ww. j  a  v a 2s  .  com

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentEncoding = connection.getContentEncoding();

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
            if ("gzip".equalsIgnoreCase(contentEncoding))
                is = new GZIPInputStream(is);

            reader = new InputStreamReader(is, Constants.UTF_8);
            final StringBuilder content = new StringBuilder();
            final long length = Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                BigDecimal btcRate = new BigDecimal(GenericUtils.toNanoCoins(rate, 0));
                                BigInteger ccnRate = btcRate.multiply(BigDecimal.valueOf(ccnBtcConversion))
                                        .toBigInteger();

                                if (ccnRate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(currencyCode, ccnRate, source));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode,
                                        url, contentEncoding, x.getMessage());
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length,
                    System.currentTimeMillis() - start);

            return rates;
        } else {
            log.warn("http status {} when fetching {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:org.apache.hadoop.hive.serde2.io.TimestampWritable.java

public static Timestamp decimalToTimestamp(BigDecimal d) {
    BigDecimal seconds = new BigDecimal(d.longValue());
    long millis = d.multiply(new BigDecimal(1000)).longValue();
    int nanos = d.subtract(seconds).multiply(new BigDecimal(1000000000)).intValue();

    Timestamp t = new Timestamp(millis);
    t.setNanos(nanos);/*from  www  . ja  v a  2  s.  c om*/

    return t;
}

From source file:org.cirdles.geoapp.LatLongToUTM.java

public static UTM convert(BigDecimal latitude, BigDecimal longitude, String datumName) {

    DatumEnum datumEnum = DatumEnum.valueOf(datumName);
    BigDecimal flattening3D = new BigDecimal(datumEnum.getFlattening3D());
    BigDecimal meridianRadius = new BigDecimal(datumEnum.getMeridianRadius());
    BigDecimal eccentricity = new BigDecimal(datumEnum.getEccentricity());

    BigDecimal latitudeRadians = latitude.abs().multiply(new BigDecimal(Math.PI)).divide(new BigDecimal(180.0),
            precision, RoundingMode.HALF_UP);

    //System.out.println("Latitude Radians: " + latitudeRadians);

    int zoneNumber = calcZoneNumber(longitude);

    BigDecimal zoneCentralMeridian = calcZoneCentralMeridian(zoneNumber);

    BigDecimal changeInLongitudeDegree = (longitude.subtract(zoneCentralMeridian)).abs().setScale(precision,
            RoundingMode.HALF_UP);
    //System.out.println("Change in Long Degree: " + changeInLongitudeDegree);

    BigDecimal changeInLongitudeRadians = (changeInLongitudeDegree.multiply(new BigDecimal(Math.PI)))
            .divide(new BigDecimal(180), precision, RoundingMode.HALF_UP);
    //System.out.println("Change In Longitude Radians: " + changeInLongitudeRadians);

    BigDecimal conformalLatitude = calcConformalLatitude(eccentricity, latitudeRadians).setScale(precision,
            RoundingMode.HALF_UP);
    //System.out.println("Conformal Latitude: " + conformalLatitude);

    BigDecimal tauPrime = (new BigDecimal(Math.tan(conformalLatitude.doubleValue()))).setScale(precision,
            RoundingMode.HALF_UP);
    //System.out.println("Tau Prime: " + tauPrime);

    BigDecimal xiPrimeNorth = calcXiPrimeNorth(changeInLongitudeRadians, tauPrime).setScale(precision,
            RoundingMode.HALF_UP);
    //System.out.println("xi Prime North: " + xiPrimeNorth);

    BigDecimal etaPrimeEast = calcEtaPrimeEast(changeInLongitudeRadians, tauPrime).setScale(precision,
            RoundingMode.HALF_UP);
    //System.out.println("Eta Prime East: " + etaPrimeEast);

    BigDecimal[] alphaSeries = { KrugerSeries.alpha1(flattening3D).setScale(precision, RoundingMode.HALF_UP),
            KrugerSeries.alpha2(flattening3D.setScale(precision, RoundingMode.HALF_UP)),
            KrugerSeries.alpha3(flattening3D).setScale(precision, RoundingMode.HALF_UP),
            KrugerSeries.alpha4(flattening3D).setScale(precision, RoundingMode.HALF_UP),
            KrugerSeries.alpha5(flattening3D).setScale(precision, RoundingMode.HALF_UP),
            KrugerSeries.alpha6(flattening3D).setScale(precision, RoundingMode.HALF_UP),
            KrugerSeries.alpha7(flattening3D).setScale(precision, RoundingMode.HALF_UP) };

    BigDecimal xiNorth = calcXiNorth(xiPrimeNorth, etaPrimeEast, alphaSeries).setScale(precision,
            RoundingMode.HALF_UP);
    //System.out.println("xi North: " + xiNorth);

    BigDecimal etaEast = calcEtaEast(xiPrimeNorth, etaPrimeEast, alphaSeries).setScale(precision,
            RoundingMode.HALF_UP);
    //System.out.println("Eta East: " + etaEast);

    BigDecimal easting = calcEasting(meridianRadius, etaEast, longitude, zoneCentralMeridian)
            .setScale(precision, RoundingMode.HALF_UP);
    BigDecimal northing = calcNorthing(meridianRadius, xiNorth, latitude).setScale(precision,
            RoundingMode.HALF_UP);

    char zoneLetter = calcZoneLetter(latitude);
    char hemisphere = calcHemisphere(latitude);

    return new UTM(easting, northing, hemisphere, zoneNumber, zoneLetter);

}

From source file:com.willetinc.hadoop.mapreduce.dynamodb.BinarySplitter.java

/**
 * Return a BigDecimal representation of byte[] array suitable for use in a
 * numerically-sorting order.//w  w w.  j ava  2  s .  c  o  m
 */
static BigDecimal byteArrayToBigDecimal(byte[] array, int maxBytes) {
    BigDecimal result = BigDecimal.ZERO;
    BigDecimal curPlace = ONE_PLACE; // start with 1/16 to compute the
    // first digit.

    int len = Math.min(array.length, maxBytes);

    for (int i = 0; i < len; i++) {
        byte codePoint = array[i];
        result = result.add(tryDivide(new BigDecimal(codePoint), curPlace));
        // advance to the next less significant place. e.g., 1/(16^2) for
        // the second char.
        curPlace = curPlace.multiply(ONE_PLACE);
    }

    return result;
}

From source file:ch.algotrader.option.OptionSymbol.java

/**
 * Generates the ISIN for the specified {@link ch.algotrader.entity.security.OptionFamily}.
 *//*  w w  w  .j a va  2  s.  c  o  m*/
public static String getIsin(OptionFamily family, LocalDate expiration, OptionType type, BigDecimal strike) {

    String week = family.isWeekly() ? DateTimePatterns.WEEK_OF_MONTH.format(expiration) : "";

    String month;
    if (OptionType.CALL.equals(type)) {
        month = monthCallEnc[expiration.getMonthValue() - 1];
    } else {
        month = monthPutEnc[expiration.getMonthValue() - 1];
    }

    int yearIndex = expiration.getYear() % 10;
    String year = yearEnc[yearIndex];

    String strike36 = BaseConverterUtil.toBase36(strike.multiply(new BigDecimal(10)).intValue());
    String strikeVal = strike.scale() + StringUtils.leftPad(strike36, 4, "0");

    StringBuilder buffer = new StringBuilder();
    buffer.append("1O");
    buffer.append(family.getIsinRoot() != null ? family.getIsinRoot() : family.getSymbolRoot());
    buffer.append(week);
    buffer.append(month);
    buffer.append(year);
    buffer.append(strikeVal);

    return buffer.toString();
}

From source file:org.cirdles.ambapo.LatLongToUTM.java

/**
 * Converts BigDecimal latitude longitude to UTM 
 * /*w  ww  . j  a  v a  2 s. com*/
 * @param latitude
 * @param longitude
 * @param datumName
 * @return UTM
 * @throws java.lang.Exception
 * 
 * 
 */
public static UTM convert(BigDecimal latitude, BigDecimal longitude, String datumName) throws Exception {

    Datum datum = Datum.valueOf(datumName);

    BigDecimal meridianRadius = new BigDecimal(datum.getMeridianRadius());
    BigDecimal eccentricity = new BigDecimal(datum.getEccentricity());

    BigDecimal latitudeRadians = latitude.abs().multiply(new BigDecimal(Math.PI)).divide(new BigDecimal(180.0),
            PRECISION, RoundingMode.HALF_UP);

    int zoneNumber = calcZoneNumber(longitude);

    BigDecimal zoneCentralMeridian = calcZoneCentralMeridian(zoneNumber);

    BigDecimal changeInLongitudeDegree = (longitude.subtract(zoneCentralMeridian)).abs().setScale(PRECISION,
            RoundingMode.HALF_UP);

    BigDecimal changeInLongitudeRadians = (changeInLongitudeDegree.multiply(new BigDecimal(Math.PI)))
            .divide(new BigDecimal(180), PRECISION, RoundingMode.HALF_UP);

    BigDecimal conformalLatitude = calcConformalLatitude(eccentricity, latitudeRadians).setScale(PRECISION,
            RoundingMode.HALF_UP);

    BigDecimal tauPrime = (new BigDecimal(Math.tan(conformalLatitude.doubleValue()))).setScale(PRECISION,
            RoundingMode.HALF_UP);

    BigDecimal xiPrimeNorth = calcXiPrimeNorth(changeInLongitudeRadians, tauPrime).setScale(PRECISION,
            RoundingMode.HALF_UP);

    BigDecimal etaPrimeEast = calcEtaPrimeEast(changeInLongitudeRadians, tauPrime).setScale(PRECISION,
            RoundingMode.HALF_UP);

    double[] alphaSeries = datum.getAlphaSeries();

    BigDecimal xiNorth = calcXiNorth(xiPrimeNorth, etaPrimeEast, alphaSeries).setScale(PRECISION,
            RoundingMode.HALF_UP);

    BigDecimal etaEast = calcEtaEast(xiPrimeNorth, etaPrimeEast, alphaSeries).setScale(PRECISION,
            RoundingMode.HALF_UP);

    BigDecimal easting = calcEasting(meridianRadius, etaEast, longitude, zoneCentralMeridian)
            .setScale(PRECISION, RoundingMode.HALF_UP);
    BigDecimal northing = calcNorthing(meridianRadius, xiNorth, latitude).setScale(PRECISION,
            RoundingMode.HALF_UP);

    char zoneLetter = calcZoneLetter(latitude);
    char hemisphere = calcHemisphere(latitude);

    if (easting.doubleValue() > UTM.MAX_EASTING)
        easting = new BigDecimal(UTM.MAX_EASTING);
    if (easting.doubleValue() < UTM.MIN_EASTING)
        easting = new BigDecimal(UTM.MIN_EASTING);

    if (northing.doubleValue() > UTM.MAX_NORTHING)
        northing = new BigDecimal(UTM.MAX_NORTHING);
    if (northing.doubleValue() < UTM.MIN_NORTHING)
        northing = new BigDecimal(UTM.MIN_NORTHING);

    UTM utm = new UTM(easting.setScale(SCALE, RoundingMode.HALF_UP),
            northing.setScale(SCALE, RoundingMode.HALF_UP), hemisphere, zoneNumber, zoneLetter);

    return utm;
}

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  w w .java 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;
}