Example usage for java.math MathContext MathContext

List of usage examples for java.math MathContext MathContext

Introduction

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

Prototype

public MathContext(int setPrecision, RoundingMode setRoundingMode) 

Source Link

Document

Constructs a new MathContext with a specified precision and rounding mode.

Usage

From source file:Main.java

public static BigDecimal log10(BigDecimal b) {
    final int NUM_OF_DIGITS = SCALE + 2;
    // need to add one to get the right number of dp
    // and then add one again to get the next number
    // so I can round it correctly.

    MathContext mc = new MathContext(NUM_OF_DIGITS, RoundingMode.HALF_EVEN);
    // special conditions:
    // log(-x) -> exception
    // log(1) == 0 exactly;
    // log of a number lessthan one = -log(1/x)
    if (b.signum() <= 0) {
        throw new ArithmeticException("log of a negative number! (or zero)");
    } else if (b.compareTo(BigDecimal.ONE) == 0) {
        return BigDecimal.ZERO;
    } else if (b.compareTo(BigDecimal.ONE) < 0) {
        return (log10((BigDecimal.ONE).divide(b, mc))).negate();
    }/*from  ww  w.  java 2 s  .c  om*/

    StringBuilder sb = new StringBuilder();
    // number of digits on the left of the decimal point
    int leftDigits = b.precision() - b.scale();

    // so, the first digits of the log10 are:
    sb.append(leftDigits - 1).append(".");

    // this is the algorithm outlined in the webpage
    int n = 0;
    while (n < NUM_OF_DIGITS) {
        b = (b.movePointLeft(leftDigits - 1)).pow(10, mc);
        leftDigits = b.precision() - b.scale();
        sb.append(leftDigits - 1);
        n++;
    }

    BigDecimal ans = new BigDecimal(sb.toString());

    // Round the number to the correct number of decimal places.
    ans = ans.round(new MathContext(ans.precision() - ans.scale() + SCALE, RoundingMode.HALF_EVEN));
    return ans;
}

From source file:Main.java

public static BigDecimal log10(BigDecimal b) {
    final int NUM_OF_DIGITS = SCALE + 2;
    // need to add one to get the right number of dp
    //  and then add one again to get the next number
    //  so I can round it correctly.

    MathContext mc = new MathContext(NUM_OF_DIGITS, RoundingMode.HALF_EVEN);
    //special conditions:
    // log(-x) -> exception
    // log(1) == 0 exactly;
    // log of a number lessthan one = -log(1/x)
    if (b.signum() <= 0) {
        throw new ArithmeticException("log of a negative number! (or zero)");
    } else if (b.compareTo(BigDecimal.ONE) == 0) {
        return BigDecimal.ZERO;
    } else if (b.compareTo(BigDecimal.ONE) < 0) {
        return (log10((BigDecimal.ONE).divide(b, mc))).negate();
    }//from  ww w .  j  ava 2  s .c o  m

    StringBuilder sb = new StringBuilder();
    //number of digits on the left of the decimal point
    int leftDigits = b.precision() - b.scale();

    //so, the first digits of the log10 are:
    sb.append(leftDigits - 1).append(".");

    //this is the algorithm outlined in the webpage
    int n = 0;
    while (n < NUM_OF_DIGITS) {
        b = (b.movePointLeft(leftDigits - 1)).pow(10, mc);
        leftDigits = b.precision() - b.scale();
        sb.append(leftDigits - 1);
        n++;
    }

    BigDecimal ans = new BigDecimal(sb.toString());

    //Round the number to the correct number of decimal places.
    ans = ans.round(new MathContext(ans.precision() - ans.scale() + SCALE, RoundingMode.HALF_EVEN));
    return ans;
}

From source file:net.vexelon.bgrates.Utils.java

public static String roundNumber(BigDecimal number, int n) {
    return number.round(new MathContext(n, RoundingMode.HALF_UP)).toPlainString();
}

From source file:r.base.MathExt.java

@Primitive
public static double signif(@Recycle double x, @Recycle int digits) {
    return new BigDecimal(x).round(new MathContext(digits, RoundingMode.HALF_UP)).doubleValue();
}

From source file:org.renjin.MathExt.java

public static double signif(double x, int digits) {
    return new BigDecimal(x).round(new MathContext(digits, RoundingMode.HALF_UP)).doubleValue();
}

From source file:au.org.ala.delta.model.attribute.SignificantFiguresAttributeChunkFormatter.java

/**
 * Overrides formatNumber in the parent class to format the number to 5 significant figures.  Trailing
 * zeros are stripped./*from w ww .  j a v a 2  s.c  om*/
 * Note: for compatibility with the original CONFOR significant figures are only applied to values after
 * the decimal place. (e.g. 123456.7 will be formatted as 123456, not 123460)
 * @param number the number to format.
 * @return the supplied number as a String.
 */
@Override
public String formatNumber(BigDecimal number) {

    int significantFigures = determinePrecision(number);
    MathContext context = new MathContext(significantFigures, RoundingMode.HALF_UP);

    BigDecimal result = number.round(context);
    result = result.stripTrailingZeros();
    return result.toPlainString();
}

From source file:fuzzy.util.MaxMF.java

public Map<Double, Double> evaluate(Collection<T> x, MembershipFunction<T> mf) {
    Map<Double, Double> max = new HashMap<Double, Double>();
    BigDecimal maxValue = BigDecimal.valueOf(0.0);
    boolean first = true;
    for (T value : x) {
        BigDecimal temp = new BigDecimal(mf.evaluate(value), new MathContext(precision, roundingMode));
        if (first || temp.compareTo(maxValue) > 0) {
            first = false;/*from w  ww  .ja v a  2 s. c o m*/
            maxValue = temp;
            max.clear();
            max.put(value.doubleValue(), temp.doubleValue());
        } else if (temp.compareTo(maxValue) == 0) {
            max.put(value.doubleValue(), temp.doubleValue());
        } // else ignore since it's less than the maximum value
    }
    return max;
}

From source file:org.homiefund.test.dao.TransactionDAOTest.java

@Test
public void create() {
    Transaction tx = new Transaction();
    tx.setRevoked(false);/*from w  w  w  .j av a2  s  .com*/
    tx.setDate(LocalDate.now());
    tx.setDescription(" create tessst ");
    tx.setOwner(userDAO.getById(1L));
    tx.setTransactionType(transactionTypeDAO.getById(4L));
    tx.setAmount(BigDecimal.valueOf(30.52));
    TransactionParticipant tp1 = new TransactionParticipant();
    tp1.setParticipant(userDAO.getById(1L));
    TransactionParticipant tp2 = new TransactionParticipant();
    tp2.setParticipant(userDAO.getById(2L));
    tx.setParticipants(new ArrayList<>(Arrays.asList(tp1, tp2)));

    Assert.assertNotNull(transactionDAO.create(tx));
    Assert.assertNotNull(tx.getId());

    BigDecimal half = tx.getAmount().divide(BigDecimal.valueOf(2L), new MathContext(2, RoundingMode.HALF_UP));
    tx.getParticipants().forEach(p -> Assert.assertEquals(half, p.getAmount()));
}

From source file:org.renjin.primitives.MathExt.java

@Deferrable
@Builtin/* w w  w  .  jav a  2 s  . c  om*/
@DataParallel
public static double signif(double x, int digits) {
    return new BigDecimal(x).round(new MathContext(digits, RoundingMode.HALF_UP)).doubleValue();
}

From source file:com.ibk.ltw.domain.Product.java

/**
 *
 * @return Price with VAT/*  w w w  .  ja va2s  .  co m*/
 */
public int getGrossPriceInCents() {
    BigDecimal grossPriceInCents = new BigDecimal(netPriceInCents)
            .multiply(new BigDecimal(1000 + vatService.getVatInPerThousand())).movePointLeft(3);
    return grossPriceInCents.round(new MathContext(0, RoundingMode.HALF_UP)).intValue();
}