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:com.mmj.app.common.util.DateViewTools.java

/**
 * ,?,/* w w  w  . ja  v a2  s  .  co  m*/
 * 
 * @param end_date
 * @param begin_date
 * @return
 */
public static String getDifferDayHourMin(Date myDate) {
    if (myDate == null) {
        return "1?";
    }
    Long currentTime = System.currentTimeMillis();
    long diff = currentTime - myDate.getTime();

    BigDecimal b1 = new BigDecimal(Long.toString(30l));
    BigDecimal b2 = new BigDecimal(Long.toString(hourPoint));
    long monthPoint = b1.multiply(b2).longValue();

    if (diff <= 0) {
        return "1?";
    } else if (diff <= secPoint) {
        return "?1?";
    } else if (diff <= minPoint) {
        return (diff / secPoint) + "?";
    } else if (diff <= hourPoint) {
        return (diff / minPoint) + "?" + ((diff % minPoint) / secPoint) + "?";
    } else if (diff <= monthPoint) {
        return (diff / hourPoint) + "" + ((diff % hourPoint) / minPoint) + "??";
    } else {
        return format(myDate, "yyyy-MM-dd HH:mm");
    }
}

From source file:Main.java

/**
 * NOTE: Arithmetic operations in primitive types may lead to arithmetic overflow. To retain
 * precision, BigDecimal objects are used.
 *
 * @param rgb//w  w w .j av  a  2  s  . c  o m
 * @return
 */
public static int[] convertRGB_8_8_8_To_HSB_32_32_32(int[] rgb) {
    int[] hsb = new int[3];
    int maxChroma = Math.max(Math.max(rgb[0], rgb[1]), rgb[2]);
    int minChroma = Math.min(Math.min(rgb[0], rgb[1]), rgb[2]);
    int diff = maxChroma - minChroma;

    // Hue
    BigDecimal hue;
    if (diff == 0) {
        hue = BigDecimal.ZERO;
    } else if (maxChroma == rgb[0]) {
        float tmp = (rgb[1] - rgb[2]) / (float) diff;
        if (tmp < 0) {
            tmp += 6 * Math.ceil(-tmp / 6.0);
        } else {
            tmp -= 6 * Math.floor(tmp / 6.0);
        }
        hue = BigDecimal.valueOf(tmp);
    } else if (maxChroma == rgb[1]) {
        hue = BigDecimal.valueOf((rgb[2] - rgb[0]) / (float) diff + 2);
    } else {
        hue = BigDecimal.valueOf((rgb[0] - rgb[1]) / (float) diff + 4);
    }
    // [0, 360] -> [0, 0xffffffff]
    hue = hue.multiply(BigDecimal.valueOf(0xffffffffL));
    hue = hue.divide(BigDecimal.valueOf(6), RoundingMode.FLOOR);
    hsb[0] = ByteBuffer.allocate(8).putLong(hue.longValue()).getInt(4);

    // Saturation
    if (maxChroma == 0) {
        hsb[1] = 0;
    } else {
        // [0, 1] -> [0, 0xffffffff]
        BigDecimal sat = BigDecimal.valueOf(diff);
        sat = sat.multiply(BigDecimal.valueOf(0xffffffffL));
        sat = sat.divide(BigDecimal.valueOf(maxChroma), RoundingMode.FLOOR);
        hsb[1] = ByteBuffer.allocate(8).putLong(sat.longValue()).getInt(4);
    }

    // Brightness
    // [0, 255] -> [0, 0xffffffff]
    BigDecimal brightness = BigDecimal.valueOf(maxChroma);
    brightness = brightness.multiply(BigDecimal.valueOf(0xffffffffL));
    brightness = brightness.divide(BigDecimal.valueOf(0xffL), RoundingMode.FLOOR);
    hsb[2] = ByteBuffer.allocate(8).putLong(brightness.longValue()).getInt(4);

    return hsb;
}

From source file:org.kuali.kpme.tklm.leave.transfer.validation.BalanceTransferValidationUtils.java

private static boolean validateTransferAmount(BigDecimal transferAmount, AccrualCategory fromCat,
        AccrualCategory toCat, String principalId, LocalDate effectiveDate, AccrualCategoryRule accrualRule) {

    //transfer amount must be less than the max transfer amount defined in the accrual category rule.
    //it cannot be negative.
    boolean isValid = true;

    BigDecimal balance = LmServiceLocator.getAccrualService().getAccruedBalanceForPrincipal(principalId,
            fromCat, effectiveDate);//from   w w  w. j av  a 2 s.c o m

    BigDecimal maxTransferAmount = null;
    BigDecimal adjustedMaxTransferAmount = null;
    if (ObjectUtils.isNotNull(accrualRule.getMaxTransferAmount())) {
        maxTransferAmount = new BigDecimal(accrualRule.getMaxTransferAmount());
        BigDecimal fullTimeEngagement = HrServiceLocator.getJobService()
                .getFteSumForAllActiveLeaveEligibleJobs(principalId, effectiveDate);
        adjustedMaxTransferAmount = maxTransferAmount.multiply(fullTimeEngagement);
    }

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

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

    if (transferAmount.compareTo(balance) > 0) {
        isValid &= false;
        GlobalVariables.getMessageMap().putError("balanceTransfer.transferAmount",
                "maxBalance.amount.exceedsBalance");
    }

    return isValid;
}

From source file:com.oracle.tutorial.jdbc.StoredProcedureJavaDBSample.java

public static void raisePrice(String coffeeName, double maximumPercentage, BigDecimal[] newPrice)
        throws SQLException {

    Connection con = DriverManager.getConnection("jdbc:default:connection");
    PreparedStatement pstmt = null;
    ResultSet rs = null;//from  w w w.j  a v a 2 s  .  c om
    BigDecimal oldPrice;

    String queryGetCurrentCoffeePrice = "select COFFEES.PRICE " + "from COFFEES "
            + "where COFFEES.COF_NAME = ?";

    pstmt = con.prepareStatement(queryGetCurrentCoffeePrice);
    pstmt.setString(1, coffeeName);
    rs = pstmt.executeQuery();

    if (rs.next()) {
        oldPrice = rs.getBigDecimal(1);
    } else {
        return;
    }

    BigDecimal maximumNewPrice = oldPrice.multiply(new BigDecimal(1 + maximumPercentage));

    // Test if newPrice[0] > maximumNewPrice

    if (newPrice[0].compareTo(maximumNewPrice) == 1) {
        newPrice[0] = maximumNewPrice;
    }

    // Test if newPrice[0] <= oldPrice

    if (newPrice[0].compareTo(oldPrice) < 1) {
        newPrice[0] = oldPrice;
        return;
    }

    String queryUpdatePrice = "update COFFEES " + "set COFFEES.PRICE = ? " + "where COFFEES.COF_NAME = ?";

    pstmt = con.prepareStatement(queryUpdatePrice);
    pstmt.setBigDecimal(1, newPrice[0]);
    pstmt.setString(2, coffeeName);
    pstmt.executeUpdate();
}

From source file:com.sunchenbin.store.feilong.core.lang.NumberUtil.java

/**
 *  multiply value./*from ww w .  j  a va2s  .  c  o  m*/
 * 
 * <p>
 * scale: (this.scale() + multiplicand.scale()).
 * </p>
 *
 * @param one
 *            
 * @param two
 *            
 * @return  <br>
 *         if isNotNullOrEmpty(two) return one
 * @see java.math.BigDecimal#multiply(BigDecimal)
 * @since 1.0.8
 */
public static BigDecimal getMultiplyValue(BigDecimal one, Serializable two) {
    if (Validator.isNullOrEmpty(two)) {
        return one;
    }

    BigDecimal multiplicand = ConvertUtil.toBigDecimal(two);
    return one.multiply(multiplicand);
}

From source file:com.aegiswallet.utils.WalletUtils.java

public static String getBTCCurrencryValue(Context context, SharedPreferences prefs, BigDecimal amount) {
    String result = "";

    File file = context.getApplicationContext().getFileStreamPath(Constants.BLOCKCHAIN_CURRENCY_FILE_NAME);
    if (file.exists()) {
        JSONObject jsonObject = BasicUtils.parseJSONData(context, Constants.BLOCKCHAIN_CURRENCY_FILE_NAME);
        try {//from w ww  . j  a v a2  s .c  o  m

            if (jsonObject != null) {

                JSONObject newObject = jsonObject
                        .getJSONObject(prefs.getString(Constants.CURRENCY_PREF_KEY, null));
                Double doubleVal = newObject.getDouble("last");
                BigDecimal decimal = BigDecimal.valueOf(doubleVal);

                result = newObject.getString("symbol")
                        + decimal.multiply(amount).setScale(2, RoundingMode.HALF_EVEN).toString();
            }
        } catch (JSONException e) {
            Log.e("Wallet Utils", "JSON Exception " + e.getMessage());
        }
    }

    return result;
}

From source file:com.aegiswallet.utils.WalletUtils.java

public static String getWalletCurrencyValue(Context context, SharedPreferences prefs, BigInteger balance) {
    String result = "";

    File file = context.getApplicationContext().getFileStreamPath(Constants.BLOCKCHAIN_CURRENCY_FILE_NAME);
    if (file.exists()) {
        JSONObject jsonObject = BasicUtils.parseJSONData(context, Constants.BLOCKCHAIN_CURRENCY_FILE_NAME);
        try {/*from w w  w . j  a  v  a 2 s  .  c o  m*/

            String balanceInBTC = balance.toString();

            if (balance.longValue() > 0)
                balanceInBTC = BasicUtils.formatValue(balance, Constants.BTC_MAX_PRECISION, 0);
            BigDecimal formattedBalance = new BigDecimal(balanceInBTC);

            if (jsonObject != null) {

                JSONObject newObject = jsonObject
                        .getJSONObject(prefs.getString(Constants.CURRENCY_PREF_KEY, null));
                Double doubleVal = newObject.getDouble("last");
                BigDecimal decimal = BigDecimal.valueOf(doubleVal);

                result = newObject.getString("symbol")
                        + decimal.multiply(formattedBalance).setScale(2, RoundingMode.HALF_EVEN).toString();
            }
        } catch (JSONException e) {
            Log.e("Wallet Utils", "JSON Exception " + e.getMessage());
        }
    }

    return result;
}

From source file:com.aoindustries.website.signup.SignupCustomizeManagementActionHelper.java

public static void setRequestAttributes(ServletContext servletContext, HttpServletRequest request,
        HttpServletResponse response, SignupSelectPackageForm signupSelectPackageForm,
        SignupCustomizeServerForm signupCustomizeServerForm,
        SignupCustomizeManagementForm signupCustomizeManagementForm) throws IOException, SQLException {
    AOServConnector rootConn = SiteSettings.getInstance(servletContext).getRootAOServConnector();
    PackageDefinition packageDefinition = rootConn.getPackageDefinitions()
            .get(signupSelectPackageForm.getPackageDefinition());
    if (packageDefinition == null)
        throw new SQLException(
                "Unable to find PackageDefinition: " + signupSelectPackageForm.getPackageDefinition());
    List<PackageDefinitionLimit> limits = packageDefinition.getLimits();

    // Get the total harddrive space in gigabytes
    int totalHardwareDiskSpace = SignupCustomizeServerActionHelper.getTotalHardwareDiskSpace(rootConn,
            signupCustomizeServerForm);//from  w  ww  . j  a  v  a 2s . c o  m

    // Find all the options
    List<Option> backupOnsiteOptions = new ArrayList<Option>();
    List<Option> backupOffsiteOptions = new ArrayList<Option>();
    List<Option> distributionScanOptions = new ArrayList<Option>();
    List<Option> failoverOptions = new ArrayList<Option>();
    for (PackageDefinitionLimit limit : limits) {
        Resource resource = limit.getResource();
        String resourceName = resource.getName();
        if (resourceName.startsWith("backup_onsite_")) {
            int limitPower = limit.getHardLimit();
            if (limitPower == PackageDefinitionLimit.UNLIMITED || limitPower > 0) {
                // This is per gigabyte of physical space
                BigDecimal additionalRate = limit.getAdditionalRate();
                if (additionalRate == null)
                    additionalRate = BigDecimal.valueOf(0, 2);
                backupOnsiteOptions.add(new Option(limit.getPkey(), resource.toString(),
                        additionalRate.multiply(BigDecimal.valueOf(totalHardwareDiskSpace))));
            }
        } else if (resourceName.startsWith("backup_offsite_")) {
            int limitPower = limit.getHardLimit();
            if (limitPower == PackageDefinitionLimit.UNLIMITED || limitPower > 0) {
                // This is per gigabyte of physical space
                BigDecimal additionalRate = limit.getAdditionalRate();
                if (additionalRate == null)
                    additionalRate = BigDecimal.valueOf(0, 2);
                backupOffsiteOptions.add(new Option(limit.getPkey(), resource.toString(),
                        additionalRate.multiply(BigDecimal.valueOf(totalHardwareDiskSpace))));
            }
        }
    }
    // Distribution scan option
    {
        Resource resource = rootConn.getResources().get(Resource.DISTRIBUTION_SCAN);
        if (resource == null) {
            servletContext.log(null,
                    new SQLException("Unable to find Resource: " + Resource.DISTRIBUTION_SCAN));
        } else {
            PackageDefinitionLimit limit = packageDefinition.getLimit(resource);
            if (limit != null) {
                int hard = limit.getHardLimit();
                if (hard == PackageDefinitionLimit.UNLIMITED || hard > 0) {
                    BigDecimal additionalRate = limit.getAdditionalRate();
                    if (additionalRate == null)
                        additionalRate = BigDecimal.valueOf(0, 2);
                    distributionScanOptions
                            .add(new Option(limit.getPkey(), resource.toString(), additionalRate));
                }
            }
        }
    }
    // Failover option
    {
        Resource resource = rootConn.getResources().get(Resource.FAILOVER);
        if (resource == null) {
            servletContext.log(null, new SQLException("Unable to find Resource: " + Resource.FAILOVER));
        } else {
            PackageDefinitionLimit limit = packageDefinition.getLimit(resource);
            if (limit != null) {
                int hard = limit.getHardLimit();
                if (hard == PackageDefinitionLimit.UNLIMITED || hard > 0) {
                    // This is per gigabyte of physical space
                    BigDecimal additionalRate = limit.getAdditionalRate();
                    if (additionalRate == null)
                        additionalRate = BigDecimal.valueOf(0, 2);
                    additionalRate = additionalRate.multiply(BigDecimal.valueOf(totalHardwareDiskSpace));
                    failoverOptions.add(new Option(limit.getPkey(), resource.toString(), additionalRate));

                    // Only once the failover option is available will the MySQL replication option be available
                    Resource mrResource = rootConn.getResources().get(Resource.MYSQL_REPLICATION);
                    if (mrResource == null) {
                        servletContext.log(null,
                                new SQLException("Unable to find Resource: " + Resource.MYSQL_REPLICATION));
                    } else {
                        PackageDefinitionLimit mrLimit = packageDefinition.getLimit(mrResource);
                        if (mrLimit != null) {
                            int mrHard = mrLimit.getHardLimit();
                            if (mrHard == PackageDefinitionLimit.UNLIMITED || mrHard > 0) {
                                BigDecimal mrAdditionalRate = mrLimit.getAdditionalRate();
                                if (mrAdditionalRate == null)
                                    mrAdditionalRate = BigDecimal.valueOf(0, 2);
                                failoverOptions.add(new Option(mrLimit.getPkey(), mrResource.toString(),
                                        additionalRate.add(mrAdditionalRate)));
                            }
                        }
                    }
                }
            }
        }
    }

    if (!backupOnsiteOptions.isEmpty())
        backupOnsiteOptions.add(0, new Option(-1, "No On-Site Backup", BigDecimal.valueOf(0, 2)));
    if (!backupOffsiteOptions.isEmpty())
        backupOffsiteOptions.add(0, new Option(-1, "No Off-Site Backup", BigDecimal.valueOf(0, 2)));
    if (!distributionScanOptions.isEmpty())
        distributionScanOptions.add(0, new Option(-1, "No daily scans", BigDecimal.valueOf(0, 2)));
    if (!failoverOptions.isEmpty())
        failoverOptions.add(0, new Option(-1, "No Fail-Over Mirror", BigDecimal.valueOf(0, 2)));

    // Sort by price
    Collections.sort(backupOnsiteOptions, new Option.PriceComparator());
    Collections.sort(backupOffsiteOptions, new Option.PriceComparator());
    Collections.sort(distributionScanOptions, new Option.PriceComparator());
    Collections.sort(failoverOptions, new Option.PriceComparator());

    // Clear any customization settings that are not part of the current package definition (this happens when they
    // select a different package type)
    if (signupCustomizeManagementForm.getBackupOnsiteOption() != -1) {
        PackageDefinitionLimit pdl = rootConn.getPackageDefinitionLimits()
                .get(signupCustomizeManagementForm.getBackupOnsiteOption());
        if (pdl == null || !packageDefinition.equals(pdl.getPackageDefinition()))
            signupCustomizeManagementForm.setBackupOnsiteOption(-1);
    }
    if (signupCustomizeManagementForm.getBackupOffsiteOption() != -1) {
        PackageDefinitionLimit pdl = rootConn.getPackageDefinitionLimits()
                .get(signupCustomizeManagementForm.getBackupOffsiteOption());
        if (pdl == null || !packageDefinition.equals(pdl.getPackageDefinition()))
            signupCustomizeManagementForm.setBackupOffsiteOption(-1);
    }
    if (signupCustomizeManagementForm.getDistributionScanOption() != -1) {
        PackageDefinitionLimit pdl = rootConn.getPackageDefinitionLimits()
                .get(signupCustomizeManagementForm.getDistributionScanOption());
        if (pdl == null || !packageDefinition.equals(pdl.getPackageDefinition()))
            signupCustomizeManagementForm.setDistributionScanOption(-1);
    }
    if (signupCustomizeManagementForm.getFailoverOption() != -1) {
        PackageDefinitionLimit pdl = rootConn.getPackageDefinitionLimits()
                .get(signupCustomizeManagementForm.getFailoverOption());
        if (pdl == null || !packageDefinition.equals(pdl.getPackageDefinition()))
            signupCustomizeManagementForm.setFailoverOption(-1);
    }

    // Store to request
    request.setAttribute("packageDefinition", packageDefinition);
    request.setAttribute("hardwareRate", SignupCustomizeServerActionHelper.getHardwareMonthlyRate(rootConn,
            signupCustomizeServerForm, packageDefinition));
    request.setAttribute("backupOnsiteOptions", backupOnsiteOptions);
    request.setAttribute("backupOffsiteOptions", backupOffsiteOptions);
    request.setAttribute("distributionScanOptions", distributionScanOptions);
    request.setAttribute("failoverOptions", failoverOptions);
}

From source file:org.openbravo.erpCommon.utility.CashVATUtil.java

/**
 * Generic method to calculate the percentage of an amount (totalAmt) with the currency's standard
 * precision/*w  ww .j a  va 2  s . c  o m*/
 * 
 * @param percentage
 *          percentage to apply for the totalAmt
 * @param totalAmt
 *          total amount (represents 100%)
 * @param currency
 *          currency
 * @return percentage * totalAmt / 100, rounded to the currency's standard precision
 */
public static BigDecimal calculatePercentageAmount(final BigDecimal percentage, final BigDecimal totalAmt,
        final Currency currency) {
    try {
        OBContext.setAdminMode(true);
        if (currency != null) {
            int precission = currency.getStandardPrecision().intValue();
            return percentage.multiply(totalAmt).divide(_100, precission, RoundingMode.HALF_UP);
        }
    } finally {
        OBContext.restorePreviousMode();
    }
    throw new RuntimeException("CashVATUtil.calculatePercentageAmount(), wrong parameters :" + percentage + ", "
            + totalAmt + ", " + currency);
}

From source file:com.webbfontaine.valuewebb.model.util.Utils.java

/**
 * multiplication is done in ordinar way and rounded and scaled after. <br/>
 * <b>if you're going to multiply and then divide</b> then use BigDecimal.multiply and then Utils.divide since it will round and scale for you.
 *//*  ww w  . j  a va 2s. c  o m*/
public static BigDecimal multiplyWithRS(BigDecimal m1, BigDecimal m2, int scale) {
    if (m1 == null || m2 == null) {
        return null;
    }
    return m1.multiply(m2).setScale(scale, getRoundingMode());
}