Example usage for java.math BigDecimal setScale

List of usage examples for java.math BigDecimal setScale

Introduction

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

Prototype

@Deprecated(since = "9")
public BigDecimal setScale(int newScale, int roundingMode) 

Source Link

Document

Returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal 's unscaled value by the appropriate power of ten to maintain its overall value.

Usage

From source file:com.cisco.dvbu.ps.deploytool.dao.jdbcapi.RegressionPerfTestDAOImpl.java

public static String printStats(long startTime) {
    String content = null;/* w ww  . ja  va  2 s  .c o m*/
    long duration = System.currentTimeMillis() - startTime;
    if (numExecs.get() == 0 || startTime <= 0 || duration <= 0) {
        return content;
    }
    // Increment the number of print stats executions which is used for averaging totals
    numStatExecs.addAndGet(1);

    // Calculate total number of executions
    execsTotal = execsTotal + numExecs.get();

    // Calculate Executions per Second or TPS - transactions per second
    double tps = numExecs.get() * 1000.0 / duration;
    BigDecimal tpsBd = new BigDecimal(tps);
    tpsBd = tpsBd.setScale(2, BigDecimal.ROUND_DOWN);
    tpsTotal = tpsTotal.add(tpsBd);

    // Calculate Rows per Execution
    double rpt = ((double) numRows.get()) / numExecs.get();
    BigDecimal rptBd = new BigDecimal(rpt);
    rptBd = rptBd.setScale(2, BigDecimal.ROUND_DOWN);
    rptTotal = rptTotal.add(rptBd);

    // Calculate Latency
    double latency = ((double) numLatency.get()) / numExecs.get();
    BigDecimal latBd = new BigDecimal(latency);
    latBd = latBd.setScale(2, BigDecimal.ROUND_DOWN);
    latTotal = latTotal.add(latBd);

    // Calculate First Row Latency
    double firstRow = ((double) firstRowLatency.get()) / numExecs.get();
    BigDecimal frBd = new BigDecimal(firstRow);
    frBd = frBd.setScale(2, BigDecimal.ROUND_DOWN);
    frTotal = frTotal.add(frBd);

    // Calculate Duration
    BigDecimal durBd = new BigDecimal(duration);
    durBd = durBd.setScale(2, BigDecimal.ROUND_DOWN);
    durTotal = durTotal.add(durBd);

    content = CommonUtils.lpad(DETAIL, 8, padChar) + logDelim
            + CommonUtils.rpad("" + numExecs.get(), 12, padChar) + logDelim
            + CommonUtils.rpad("" + tpsBd, 12, padChar) + logDelim + CommonUtils.rpad("" + rptBd, 12, padChar)
            + logDelim + CommonUtils.rpad("" + latBd, 13, padChar) + logDelim
            + CommonUtils.rpad("" + frBd, 13, padChar) + logDelim + CommonUtils.rpad("" + durBd, 20, padChar)
            + logDelim + logDelim;
    RegressionManagerUtils.printOutputStr(printOutputType, "summary", content, "");
    content += "\n";
    /*
     * Execs       Execs/sec   Rows/exec   Latency (ms) 1st row (ms) Duration (ms)
    *   1191        237.86      9.00        4.19         4.19        5000 
    *   1387        276.90      9.00        3.61         3.61        5003
     */
    return content;
}

From source file:Main.java

/**
 * Compute the natural logarithm of x to a given scale, x > 0.
 * Use Newton's algorithm./*  w ww. j  av a  2 s . c  om*/
 */
private static BigDecimal lnNewton(BigDecimal x, int scale) {
    int sp1 = scale + 1;
    BigDecimal n = x;
    BigDecimal term;

    // Convergence tolerance = 5*(10^-(scale+1))
    BigDecimal tolerance = BigDecimal.valueOf(5).movePointLeft(sp1);

    // Loop until the approximations converge
    // (two successive approximations are within the tolerance).
    do {

        // e^x
        BigDecimal eToX = exp(x, sp1);

        // (e^x - n)/e^x
        term = eToX.subtract(n).divide(eToX, sp1, BigDecimal.ROUND_DOWN);

        // x - (e^x - n)/e^x
        x = x.subtract(term);

        Thread.yield();
    } while (term.compareTo(tolerance) > 0);

    return x.setScale(scale, BigDecimal.ROUND_HALF_EVEN);
}

From source file:org.kuali.kpme.core.util.TKUtils.java

public static BigDecimal getHoursBetween(long start, long end) {
    long diff = end - start;
    BigDecimal hrsReminder = new BigDecimal((diff / 3600000.0) % 24);
    // if the hours is exact duplicate of 24 hours
    if (hrsReminder.compareTo(BigDecimal.ZERO) == 0 && diff > 0) {
        return new BigDecimal(diff / 3600000.0)
                .setScale(HrConstants.BIG_DECIMAL_SCALE, HrConstants.BIG_DECIMAL_SCALE_ROUNDING).abs();
    }// w  w w  .ja v a2  s  .  c o  m
    return hrsReminder.setScale(HrConstants.BIG_DECIMAL_SCALE, HrConstants.BIG_DECIMAL_SCALE_ROUNDING).abs();
}

From source file:com.icebreak.p2p.trade.impl.InvestServiceImpl.java

private static double getDaysRuleRate(double rule, Trade trade, Date endDate) {
    String timeLimitUnit = trade.getTimeLimitUnit();
    double timeLimit = trade.getTimeLimit();
    double days = 0;
    if (LoanLimitUnitEnum.LOAN_BY_DAY.code().equals(timeLimitUnit)) {
        days = timeLimit;//from w  ww.  ja va 2  s. c  o  m
    } else if (LoanLimitUnitEnum.LOAN_BY_YEAR.code().equals(timeLimitUnit)) {
        days = timeLimit * YrdConstants.TimeRelativeConstants.DAYSOFAYEAR;
    } else {
        days = Math.round(timeLimit * YrdConstants.TimeRelativeConstants.DAYSOFAYEAR / 12);
    }
    //?? ??
    if (null != trade.getEffectiveDateTime()) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar endTime = Calendar.getInstance();
            if (null == endDate) {
                endTime.setTime(sdf.parse(sdf.format(Calendar.getInstance().getTime())));
            } else {
                endTime.setTime(sdf.parse(sdf.format(endDate)));
            }
            Calendar beginTime = Calendar.getInstance();
            beginTime.setTime(sdf.parse(sdf.format(trade.getEffectiveDateTime())));
            int cutDays = (int) ((endTime.getTimeInMillis() - beginTime.getTimeInMillis()) / 1000 / 60 / 60
                    / 24);
            days = days - cutDays;
            days = (days < 0 ? 0 : days);
        } catch (Exception e) {
            Logger logger = LoggerFactory.getLogger("get DiffDate");
            logger.error("conculate diffDate throw a exceptioin!");
            logger.error(e.getMessage());
        }
    }
    BigDecimal bg = new BigDecimal(rule / YrdConstants.TimeRelativeConstants.DAYSOFAYEAR * days);
    double daysRate = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
    return daysRate;
}

From source file:com.guodong.sun.guodong.uitls.CacheUtil.java

public static String getFormatSize(double size) {
    double kiloByte = size / 1024;
    if (kiloByte < 1) {
        //            return size + "Byte";
        return "0K";
    }/*  w ww .j  av a2  s .c om*/

    double megaByte = kiloByte / 1024;
    if (megaByte < 1) {
        BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
        return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
    }

    double gigaByte = megaByte / 1024;
    if (gigaByte < 1) {
        BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
        return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
    }

    double teraBytes = gigaByte / 1024;
    if (teraBytes < 1) {
        BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
        return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
    }
    BigDecimal result4 = new BigDecimal(teraBytes);
    return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
}

From source file:de.micromata.genome.util.types.Converter.java

/**
 * Creates the amount.//from w  w w  . j  ava 2 s. c  om
 *
 * @param amount the amount
 * @return the big decimal
 */
public static BigDecimal createAmount(double amount) {
    BigDecimal bd = new BigDecimal(amount);
    bd = bd.setScale(2, RoundingMode.HALF_UP);
    return bd;
}

From source file:com.xumpy.thuisadmin.services.implementations.BedragenSrvImpl.java

public static BigDecimal convertComma(String bedrag) {
    if (bedrag.contains(",")) {
        bedrag = bedrag.replace(".", "");
        bedrag = bedrag.replace(",", ".");
    } else {//  w  ww .j a  v  a  2s.  c  om
        if (bedrag.indexOf(".", bedrag.indexOf(".") + 1) != -1) {
            bedrag = bedrag.replace(".", "");
        }
    }

    NumberFormat nf = NumberFormat.getInstance(new Locale("US"));
    BigDecimal bigDecimalBedrag = new BigDecimal(0);
    try {
        bigDecimalBedrag = new BigDecimal(nf.parse(bedrag).doubleValue());
    } catch (ParseException ex) {
        Logger.getLogger(BedragenSrvImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    bigDecimalBedrag = bigDecimalBedrag.setScale(2, BigDecimal.ROUND_HALF_UP);

    return bigDecimalBedrag;
}

From source file:ru.anr.base.BaseParent.java

/**
 * Short-cut for set a scale for {@link BigDecimal} using the standard
 * {@link RoundingMode#HALF_UP} mode (so called 'school' rounding).
 * /*w w  w. j  av  a2s . c o  m*/
 * @param d
 *            A decimal value
 * @param scale
 *            The scale
 * @return New {@link BigDecimal} in the specified scale
 */
public static final BigDecimal scale(BigDecimal d, int scale) {

    return d.setScale(scale, RoundingMode.HALF_UP);
}

From source file:kenh.expl.functions.Round.java

public double process(double number, int scale) {
    BigDecimal b = new BigDecimal(number);
    number = b.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    return number;
}

From source file:com.eveonline.api.repo.AccountBalanceTests.java

@Test
@Sql({ "/testGetAccountKey1000Balance.sql" })
public void testGetAccountKey1000Balance() {
    AccountBalance balance = repo.findByAccountKeyAndCorporationId(1000, 1l);
    BigDecimal expected = new BigDecimal(200000.35);
    expected = expected.setScale(2, BigDecimal.ROUND_HALF_UP);
    assertEquals("Incorrect balance for corp and account key", expected, balance.getBalance());
}