List of usage examples for java.math BigDecimal scale
int scale
To view the source code for java.math BigDecimal scale.
Click Source Link
From source file:org.pentaho.di.jdbc.Support.java
/** * Normalize a BigDecimal value so that it fits within the * available precision./*from w w w .ja v a 2 s. c o m*/ * * @param value The decimal value to normalize. * @param maxPrecision The decimal precision supported by the server * (assumed to be a value of either 28 or 38). * @return The possibly normalized decimal value as a <code>BigDecimal</code>. * @throws SQLException If the number is too big. */ static BigDecimal normalizeBigDecimal(BigDecimal value, int maxPrecision) throws SQLException { if (value == null) { return null; } if (value.scale() < 0) { // Java 1.5 BigDecimal allows negative scales. // jTDS cannot send these so re-scale. value = value.setScale(0); } if (value.scale() > maxPrecision) { // This is an optimization to quickly adjust the scale of a // very precise BD value. For example // BigDecimal((double)1.0/3.0) yields a BD 54 digits long! value = value.setScale(maxPrecision, BigDecimal.ROUND_HALF_UP); } BigInteger max = MAX_VALUE_38; while (value.abs().unscaledValue().compareTo(max) > 0) { // OK we need to reduce the scale if possible to preserve // the integer part of the number and still fit within the // available precision. int scale = value.scale() - 1; if (scale < 0) { // Can't do it number just too big throw new SQLException( BaseMessages.getString(PKG, "error.normalize.numtoobig", String.valueOf(maxPrecision)), "22000"); } value = value.setScale(scale, BigDecimal.ROUND_HALF_UP); } return value; }
From source file:org.projectforge.web.wicket.converter.BigDecimalPercentConverter.java
@Override public BigDecimal convertToObject(String value, final Locale locale) { value = StringUtils.trimToEmpty(value); if (value.endsWith("%") == true) { value = value.substring(0, value.length() - 1).trim(); }/*w ww . java 2 s . c o m*/ BigDecimal bd = super.convertToObject(value, locale); if (bd != null && decimalFormat == true) { bd = bd.divide(NumberHelper.HUNDRED, bd.scale() + 2, RoundingMode.HALF_UP); } return bd; }
From source file:eu.bittrade.libs.steemj.protocol.Asset.java
/** * Set the amount of this asset.//from ww w . j a v a2s. c o m * * @param amount * The amount. */ public void setAmount(BigDecimal amount) { if (amount.scale() > this.getPrecision()) { throw new InvalidParameterException("The provided 'amount' has a 'scale' of " + amount.scale() + ", but needs to have a 'scale' of " + this.getPrecision() + " when " + this.getSymbol().name() + " is used as a AssetSymbolType."); } this.amount = amount.multiply(BigDecimal.valueOf(Math.pow(10, this.getPrecision()))).longValue(); }
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 w ww. ja va2s .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: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 w w w .j av a 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:org.osaf.cosmo.eim.schema.text.TriageStatusFormat.java
public Object parseObject(String source, ParsePosition pos) { if (pos.getIndex() > 0) return null; int index = 0; String[] chunks = source.split(" ", 3); if (chunks.length != 3) { parseException = new ParseException("Incorrect number of chunks: " + chunks.length, 0); pos.setErrorIndex(index);/*from ww w .j ava2s. co m*/ return null; } TriageStatus ts = entityFactory.createTriageStatus(); try { pos.setIndex(index); Integer code = new Integer(chunks[0]); // validate the code as being known TriageStatusUtil.label(code); ts.setCode(code); index += chunks[0].length() + 1; } catch (Exception e) { parseException = new ParseException(e.getMessage(), 0); pos.setErrorIndex(index); return null; } try { pos.setIndex(index); BigDecimal rank = new BigDecimal(chunks[1]); if (rank.scale() != 2) throw new NumberFormatException("Invalid rank value " + chunks[1]); ts.setRank(rank); index += chunks[1].length() + 1; } catch (NumberFormatException e) { parseException = new ParseException(e.getMessage(), 0); pos.setErrorIndex(index); return null; } if (chunks[2].equals(AUTOTRIAGE_ON)) ts.setAutoTriage(Boolean.TRUE); else if (chunks[2].equals(AUTOTRIAGE_OFF)) ts.setAutoTriage(Boolean.FALSE); else { parseException = new ParseException("Invalid autotriage value " + chunks[2], 0); pos.setErrorIndex(index); return null; } index += chunks[2].length(); pos.setIndex(index); return ts; }
From source file:com.rabbitmq.client.impl.ValueWriter.java
public final void writeFieldValue(Object value) throws IOException { if (value instanceof String) { writeOctet('S'); writeLongstr((String) value); } else if (value instanceof LongString) { writeOctet('S'); writeLongstr((LongString) value); } else if (value instanceof Integer) { writeOctet('I'); writeLong((Integer) value); } else if (value instanceof BigDecimal) { writeOctet('D'); BigDecimal decimal = (BigDecimal) value; writeOctet(decimal.scale()); BigInteger unscaled = decimal.unscaledValue(); if (unscaled.bitLength() > 32) /*Integer.SIZE in Java 1.5*/ throw new IllegalArgumentException("BigDecimal too large to be encoded"); writeLong(decimal.unscaledValue().intValue()); } else if (value instanceof Date) { writeOctet('T'); writeTimestamp((Date) value); } else if (value instanceof Map) { writeOctet('F'); // Ignore the warnings here. We hate erasure // (not even a little respect) // (We even have trouble recognising it.) @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) value; writeTable(map);// w w w . j av a2s . c o m } else if (value instanceof Byte) { writeOctet('b'); out.writeByte((Byte) value); } else if (value instanceof Double) { writeOctet('d'); out.writeDouble((Double) value); } else if (value instanceof Float) { writeOctet('f'); out.writeFloat((Float) value); } else if (value instanceof Long) { writeOctet('l'); out.writeLong((Long) value); } else if (value instanceof Short) { writeOctet('s'); out.writeShort((Short) value); } else if (value instanceof Boolean) { writeOctet('t'); out.writeBoolean((Boolean) value); } else if (value instanceof byte[]) { writeOctet('x'); writeLong(((byte[]) value).length); out.write((byte[]) value); } else if (value == null) { writeOctet('V'); } else if (value instanceof List) { writeOctet('A'); writeArray((List<?>) value); } else { throw new IllegalArgumentException("Invalid value type: " + value.getClass().getName()); } }
From source file:au.org.ala.sds.util.GeneralisedLocation.java
private String round(String number, int decimalPlaces) { if (number == null || number.equals("")) { return ""; } else {/*from ww w . j ava2s . c om*/ BigDecimal bd = new BigDecimal(number); if (bd.scale() > decimalPlaces) { return String.format("%." + decimalPlaces + "f", bd); } else { return number; } } }
From source file:org.key2gym.business.services.CashServiceBean.java
/** * Validates a money amount.//from ww w.j a v a2 s.c o m * * @param value the amount to validate * @throws ValidationException if the amount is invalid */ public void validateAmount(BigDecimal value) throws ValidationException { if (value == null) { throw new NullPointerException("The amount is null."); //NOI18N } if (value.scale() > 2) { throw new ValidationException(getString("Invalid.Money.TwoDigitsAfterDecimalPointMax")); } value = value.setScale(2); if (value.precision() > 6) { throw new ValidationException(getString("Invalid.CashAdjustment.LimitReached")); } }
From source file:jp.terasoluna.fw.validation.ValidationUtil.java
/** * ??????????/*w w w . j ava 2s . c om*/ * <br> * ?????????????? * <ul> * <li>??? * <ol> * <li><code>isAccordedInteger</code>?<code>true</code>??? * ????<code>integerLength</code>?? * ???????? * * <li><code>isAccordedInteger</code>?<code>false</code>??? * ????<code>integerLength</code>????? * ?? * </ol> * * <li>???? * <ol> * <li><code>isAccordedScale</code>?<code>true</code>??? * ?????<code>scaleLength</code>?? * ???????? * * <li><code>isAccordedScale</code>?<code>true</code>??? * ?????<code>scaleLength</code>????? * ?? * </ol> * </ul> * * @param value * @param integerLength ?? * @param isAccordedInteger * ?????? * <code>true</code>? * ?????? * <code>false</code>? * @param scaleLength ??? * @param isAccordedScale * ??????? * <code>true</code>? * ??????? * <code>false</code>? * * @return * ???????? * <code>true</code>? * ?????<code>false</code>? */ public static boolean isNumber(BigDecimal value, int integerLength, boolean isAccordedInteger, int scaleLength, boolean isAccordedScale) { // ?null??true? if (value == null) { return true; } // ?? // ?? BigInteger bi = value.toBigInteger().abs(); // ? int length = bi.toString().length(); if (!checkNumberFigures(length, integerLength, isAccordedInteger)) { return false; } // ??? int scale = value.scale(); if (!checkNumberFigures(scale, scaleLength, isAccordedScale)) { return false; } return true; }