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:org.jvnet.hudson.plugins.backup.utils.BackupTask.java

public void run() {
    assert (logFilePath != null);
    assert (configuration.getFileNameTemplate() != null);

    SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);

    startDate = new Date();
    try {//w w w .jav  a  2 s  .co  m
        logger = new BackupLogger(logFilePath, configuration.isVerbose());
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Unable to open log file for writing: {0}", logFilePath);
        return;
    }

    logger.info("Backup started at " + getTimestamp(startDate));

    // Have to include shutdown time in backup time ?
    waitNoJobsInQueue();

    // file filter specific to what's inside jobs' worskpace
    IOFileFilter jobsExclusionFileFilter = null;

    // Creating global exclusions
    List<String> exclusions = new ArrayList<String>();
    exclusions.addAll(Arrays.asList(DEFAULT_EXCLUSIONS));
    exclusions.addAll(configuration.getCustomExclusions());
    if (!configuration.getKeepWorkspaces()) {
        exclusions.add(WORKSPACE_NAME);
    } else {
        jobsExclusionFileFilter = createJobsExclusionFileFilter(hudsonWorkDir, configuration.getJobIncludes(),
                configuration.getJobExcludes(), configuration.getCaseSensitive());
    }
    if (!configuration.getKeepFingerprints()) {
        exclusions.add(FINGERPRINTS_NAME);
    }
    if (!configuration.getKeepBuilds()) {
        exclusions.add(BUILDS_NAME);
    }
    if (!configuration.getKeepArchives()) {
        exclusions.add(ARCHIVE_NAME);
    }

    IOFileFilter filter = createFileFilter(exclusions, jobsExclusionFileFilter);

    try {
        BackupEngine backupEngine = new BackupEngine(logger, hudsonWorkDir, backupFileName,
                configuration.getArchiveType().getArchiver(), filter);
        backupEngine.doBackup();
    } catch (BackupException e) {
        e.printStackTrace(logger.getWriter());
    } finally {
        cancelNoJobs();

        endDate = new Date();
        logger.info("Backup end at " + getTimestamp(endDate));
        BigDecimal delay = new BigDecimal(endDate.getTime() - startDate.getTime());
        delay = delay.setScale(2, BigDecimal.ROUND_HALF_UP);
        delay = delay.divide(new BigDecimal("1000"));

        logger.info("[" + delay.toPlainString() + "s]");

        finished = true;
        logger.close();
    }
}

From source file:com.salesmanager.core.module.impl.application.currencies.EURCurrencyModule.java

public String getMeasure(BigDecimal measure, String currencycode) throws Exception {

    NumberFormat nf = null;/*from  w  ww  .java 2s.  com*/

    nf = NumberFormat.getInstance(Locale.GERMAN);

    nf.setMaximumFractionDigits(1);
    nf.setMinimumFractionDigits(1);

    measure.setScale(1, BigDecimal.ROUND_HALF_UP);

    return nf.format(measure);
}

From source file:dk.clanie.money.Money.java

/**
 * Divide evenly into parts.//from   w ww .  j  a v  a 2 s. c  o m
 * 
 * Divides an amount into parts of approximately the same size while
 * ensuring that the sum of all the parts equals the whole.
 * <p>
 * Parts of unequal size will be distributed evenly in the returned array.
 * <p>
 * For example, if asked to divede 20 into 6 parts the result will be {3.33,
 * 3.34, 3.33, 3.33, 3.34, 3.33}
 * 
 * @param parts -
 *            number of parts
 * @return Money[] with the parts
 */
public Money[] divideEvenlyIntoParts(int parts) {
    Money[] res = new Money[parts];
    final BigDecimal bdParts = new BigDecimal(parts);
    final MathContext mc = MathContext.DECIMAL128;
    BigDecimal sumOfPreviousParts = BigDecimal.ZERO;
    for (int i = 0; i < parts; i++) {
        Money part = new Money();
        BigDecimal sumOfParts = amount.multiply(new BigDecimal(i + 1));
        sumOfParts = sumOfParts.divide(bdParts, mc);
        sumOfParts = sumOfParts.setScale(amount.scale(), mc.getRoundingMode());
        part.amount = sumOfParts.subtract(sumOfPreviousParts);
        sumOfPreviousParts = sumOfParts;
        part.currency = currency;
        res[i] = part;
    }
    return res;
}

From source file:Money.java

/**
 * returns Money .  If roundCeiling is true we rounded up to
 * the nearest cent, otherwise we round down.  Note that rounding toward the ceiling
 * always rounds to positive infinity (so, for example, -$0.031 becomes
 * -$0.03).   When roundCeiling is false we round toward the floor, so in that case
 * -$0.031 becomes-$0.04.  This is exactly as BigDecimal.ROUND_CEILING and
 * BigDecimal.ROUND_FLOOR behave.//from   w  w  w . ja  v  a2  s  .c  o  m
 * @see java.math.BigDecimal.ROUND_CEILING
 */
public Money multiplyAndRound(BigDecimal val, boolean roundCeiling) {
    BigDecimal product = delegate.multiply(val);
    int rounding = roundCeiling ? BigDecimal.ROUND_CEILING : BigDecimal.ROUND_FLOOR;
    return new Money(product.setScale(2, rounding));
}

From source file:net.lizalab.util.RdRandRandomTest.java

/**
 * Runs the Monte Carlo Pi approximation test for the specified
 * instance of Random./*from   ww w  .j  ava  2  s. c o  m*/
 * @param random The RNG instance to test.
 * @param doAssert Flag to indicate whether result should be asserted or simply logged.
 */
private void monteCarloPiTest(Random random, boolean doAssert) {
    final String methodName = "monteCarloPiTest : ";

    int inRandCircle = 0;

    // xr and yr will be the random point
    // zr will be the calculated distance to the center
    double xr, yr, zr;

    long start = System.currentTimeMillis();
    for (int i = 0; i < numPoints; i++) {
        xr = random.nextDouble();
        yr = random.nextDouble();

        zr = (xr * xr) + (yr * yr);
        if (zr <= 1.0) {
            inRandCircle++;
        }
    }
    long end = System.currentTimeMillis();
    LOGGER.info("{} Time: {}ms", methodName, end - start);

    // calculate the Pi approximations
    double randomPi = (double) inRandCircle / numPoints * 4.0;

    // calculate the difference and % error
    double diff = (randomPi - Math.PI);
    double randomError = diff / Math.PI * 100;
    LOGGER.info("{} Pi Approximation: {}, Diff: {}, Error %: {}", methodName, randomPi, diff, randomError);
    BigDecimal randomPiBD = new BigDecimal(randomPi);
    randomPiBD = randomPiBD.setScale(precision - 1, RoundingMode.DOWN);
    // Verify result.
    boolean result = randomPiBD.compareTo(pi) == 0;
    String msg = "Pi approximation not sufficiently precise for " + random.getClass();
    if (doAssert) {
        assertTrue(msg, result);
    } else {
        if (!result) {
            LOGGER.warn("{} {}", methodName, msg);
        }
    }
}

From source file:org.kalypso.kalypsomodel1d2d.conv.results.ResultMeta1d2dHelper.java

public static Date parseTimelineHour(final String hourString, final int year) {
    final BigDecimal hours = NumberUtils.parseQuietDecimal(hourString);
    if (hours == null)
        return null;

    // REMARK: we read the calculation core time with the time zone, as defined in Kalypso Preferences
    final Calendar calendar = Calendar.getInstance(KalypsoCorePlugin.getDefault().getTimeZone());
    calendar.clear();/*from   www .  ja v a 2s. c  o m*/
    calendar.set(year, 0, 1);

    BigDecimal wholeHours = hours.setScale(0, BigDecimal.ROUND_DOWN);
    final BigDecimal wholeMinutes = hours.subtract(wholeHours).multiply(new BigDecimal("60")); //$NON-NLS-1$
    if (wholeHours.intValue() > 1) {
        wholeHours = new BigDecimal(wholeHours.intValue() - 1);
    }
    calendar.add(Calendar.HOUR, wholeHours.intValue());
    calendar.add(Calendar.MINUTE, wholeMinutes.intValue());

    final boolean lBoolLeapYear = DateUtilities.isLeapYear(calendar);
    if (lBoolLeapYear && calendar.get(Calendar.DAY_OF_YEAR) > 59) {
        calendar.clear();
        calendar.set(year, 0, 1);
        calendar.add(Calendar.HOUR, wholeHours.intValue() - 24);
        calendar.add(Calendar.MINUTE, wholeMinutes.intValue());
    }

    return calendar.getTime();
}

From source file:com.qcadoo.model.internal.units.UnitConversionImpl.java

private UnitConversionImpl(final String unitFrom, final String unitTo, final BigDecimal ratio,
        final MathContext mathContext) {
    Preconditions.checkNotNull(unitFrom);
    Preconditions.checkNotNull(ratio);//  w  w w  . j  av a2s.  com
    Preconditions.checkNotNull(mathContext);

    this.unitFrom = unitFrom;
    this.unitTo = unitTo;
    this.ratio = ratio.setScale(mathContext.getPrecision(), mathContext.getRoundingMode());
    this.mathContext = mathContext;
}

From source file:org.efaps.esjp.assets.LifecycleCostAbstract_Base.java

protected void createCost(final Parameter _parameter) throws EFapsException {
    // Sales-Configuration
    final Instance baseCurrInst = Currency.getBaseCurrency();

    final Instance rateCurrInst = _parameter.getParameterValue("rateCurrencyLink") == null ? baseCurrInst
            : Instance.get(CIERP.Currency.getType(), _parameter.getParameterValue("rateCurrencyLink"));

    final Object[] rateObj = new BigDecimal[] { BigDecimal.ONE, BigDecimal.ONE };
    final BigDecimal rate = ((BigDecimal) rateObj[0]).divide((BigDecimal) rateObj[1], 12,
            BigDecimal.ROUND_HALF_UP);

    final DecimalFormat format = getFormatInstance();
    final Insert insert = new Insert(getType4CostCreate(_parameter));
    insert.add(CIAssets.LifecycleCostAbstract.AssetLinkAbstract, _parameter.getInstance().getId());
    insert.add(CIAssets.LifecycleCostAbstract.RateCurrencyLink, rateCurrInst.getId());
    insert.add(CIAssets.LifecycleCostAbstract.CurrencyLink, baseCurrInst.getId());
    insert.add(CIAssets.LifecycleCostAbstract.Rate, rateObj);

    final String date = _parameter
            .getParameterValue(getFieldName4Attribute(_parameter, CIAssets.LifecycleCostAbstract.Date.name));
    if (date != null) {
        insert.add(CIAssets.LifecycleCostAbstract.Date, date);
    }/*from w  w  w.  j a  va 2  s.c o m*/

    final String rateAmountStr = _parameter.getParameterValue(
            getFieldName4Attribute(_parameter, CIAssets.LifecycleCostAbstract.RateAmount.name));
    if (rateAmountStr != null) {
        try {
            final BigDecimal rateAmount = (BigDecimal) format.parse(rateAmountStr);
            insert.add(CIAssets.LifecycleCostAbstract.RateAmount, rateAmount);
            insert.add(CIAssets.LifecycleCostAbstract.Amount,
                    rateAmount.setScale(8, BigDecimal.ROUND_HALF_UP).divide(rate, BigDecimal.ROUND_HALF_UP));
        } catch (final ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    insert.execute();
}

From source file:no.digipost.print.validate.PdfValidator.java

private double mmToPoints(final int sizeInMillimeters) {
    BigDecimal points = new BigDecimal(sizeInMillimeters * MM_TO_POINTS);
    points = points.setScale(1, RoundingMode.DOWN);
    return points.doubleValue();
}

From source file:com.ar.dev.tierra.api.dao.impl.FiscalDAOImpl.java

@Override
public void ticket(List<DetalleFactura> detalles) {
    try (PrintWriter ticket = new PrintWriter("command/ticket.200")) {
        DecimalFormat decimalFormat = new DecimalFormat();
        decimalFormat.setMaximumFractionDigits(1);
        ticket.println("@" + (char) 28 + "T" + (char) 28 + "T");
        BigDecimal descuento = new BigDecimal(BigInteger.ZERO);
        for (DetalleFactura detalle : detalles) {
            if (detalle.getDescuentoDetalle() != null) {
                descuento = descuento.add(detalle.getDescuentoDetalle());
            }/*from  w w w  .ja  v a  2 s.c  o m*/
            String price = null;
            BigDecimal sinIVA = detalle.getProducto().getPrecioVenta().subtract(detalle.getProducto()
                    .getPrecioVenta().multiply(new BigDecimal(17.35)).divide(new BigDecimal(100)));
            price = sinIVA.setScale(4, RoundingMode.HALF_UP).toString();
            ticket.println("B" + (char) 28 /*Abrimos linea*/
                    + detalle.getProducto().getDescripcion() + (char) 28 /*Nombre producto*/
                    + detalle.getCantidadDetalle() + ".0" + (char) 28 /*Cantidad*/
                    + price.replace(",", ".") + (char) 28 /*Precio unitario*/
                    + "21.0" + (char) 28 /*Impuestos IVA*/
                    + "M" + (char) 28 /*Suma monto*/
                    + "0.0" + (char) 28 /*Impuestos internos*/
                    + "0" + (char) 28 /*Parametro display*/
                    + "b");
            /*Cierra de linea*/
        }
        if (!descuento.equals(new BigDecimal(BigInteger.ZERO))) {
            ticket.println("T" + (char) 28 /*Abrimos linea descuento*/
                    + "Descuento: " + (char) 28 /*Texto a mostrar*/
                    + descuento + (char) 28 /*Monto descuento*/
                    + "m" + (char) 28 /*m: descuento, M: aumento*/
                    + "0" + (char) 28 /*parametro display*/
                    + "T");
            /*cierre linea descuento*/
        }
        ticket.println("E");
    } catch (FileNotFoundException ex) {
        Logger.getLogger(FiscalDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
}