List of usage examples for java.math BigDecimal precision
int precision
To view the source code for java.math BigDecimal precision.
Click Source Link
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(); }/*www .ja va 2s. 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:au.org.ala.delta.model.attribute.SignificantFiguresAttributeChunkFormatter.java
/** * Determines the precision to format the number to. * @param number the number to determine. * @return the precision (number of figures) to format the supplied number to. *///w w w . j a va 2 s .co m private int determinePrecision(BigDecimal number) { // Adjust the precision because CONFOR doesn't strictly do significant figures - it only applies them // to values after the decimal place. // e.g. 123456.78 to 5 significant figures should be 123460 but CONFOR will output 123456 int digitsToLeftOfPoint = number.precision() - number.scale(); return Math.max(NUM_SIGNIFICANT_FIGURES, digitsToLeftOfPoint); }
From source file:ccc.cli.StringToDecConverterUtil.java
/** * * Converts a number represented as text to a decimal number. * * @param textNumber text representation of a number * @return BigDecimal//from w ww . jav a 2 s .co m */ public BigDecimal convert(final String textNumber) { BigDecimal decNumber = null; if (textNumber != null && textNumber.matches(DECIMAL_PATTERN)) { // BigNumber(String) constructor does not allow commas decNumber = new BigDecimal(textNumber.replaceAll(",", "")); if (decNumber.precision() > MAX_PRECISION || decNumber.scale() < 0 && Math.abs(decNumber.scale()) + decNumber.precision() > MAX_PRECISION - MAX_SCALE || decNumber.compareTo(MAX_VALUE) == 1) { LOG.warn("Value is larger than maximum precision allowed " + "and was rejected."); return null; } if (decNumber.scale() > MAX_SCALE) { LOG.trace("Scale is bigger than maximum allowed: " + decNumber.scale() + ". Resetting scale."); decNumber = decNumber.setScale(MAX_SCALE, RoundingMode.DOWN); } } return decNumber; }
From source file:com.autentia.intra.validator.EuroValidator.java
/** */ public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { int scale = Integer.parseInt((String) component.getAttributes().get("scale")); int maxSize = Integer.parseInt((String) component.getAttributes().get("maxSize")); log.info("validate - value=" + value); if (value != null) { // Check if value is a BigDecimal if (!(value instanceof BigDecimal)) { log.info("validate - value is not a BigDecimal (" + value.getClass().getName() + ")"); throw new ValidatorException( new FacesMessage("Las cantidades monetarias deben ser de tipo BigDecimal")); }//w ww .j av a 2 s. c o m // Check if it has no more than scale decimal digits BigDecimal bd = (BigDecimal) value; if (bd.scale() > scale) { log.info("validate - value has more than 2 decimals (" + value + ")"); throw new ValidatorException(new FacesMessage( "Las cantidades monetarias no pueden tener ms de " + scale + " decimales")); } if (bd.precision() - bd.scale() > (maxSize - scale)) { log.info("validate - value has more than " + maxSize + " numbers (" + value + ")"); throw new ValidatorException(new FacesMessage("Las cantidades monetarias no pueden tener ms de " + maxSize + " cifras incluyendo los " + scale + " decimales")); } } }
From source file:org.key2gym.business.services.CashServiceBean.java
/** * Validates a money amount./*from w ww . j ava 2 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:sbml.test.UploadUnzipTest.java
private final boolean tolerable(double expectedVal, double actualVal, double absTol, double relTol) { if (Double.isInfinite(expectedVal)) return (expectedVal == actualVal); else if (Double.isNaN(expectedVal)) return Double.isNaN(actualVal); else if (Double.isNaN(actualVal) || Double.isInfinite(actualVal)) return false; else {//from w w w. j a v a 2s .c om BigDecimal expected = new BigDecimal(expectedVal); MathContext mc = new MathContext(expected.precision()); BigDecimal adjusted = new BigDecimal(actualVal).round(mc); BigDecimal actualDiff = expected.subtract(adjusted).abs(); BigDecimal rtol = new BigDecimal(relTol); BigDecimal atol = new BigDecimal(absTol); BigDecimal allowableDiff = atol.add(rtol.multiply(expected.abs())); return (actualDiff.compareTo(allowableDiff) <= 0); } }
From source file:tasly.greathealth.erp.order.services.impl.DefaultOrderUpdateService.java
private BigDecimal double2BigDecimal(final double refundAmount) { final BigDecimal decimal = new BigDecimal(Double.toString(refundAmount)); decimal.setScale(3, BigDecimal.ROUND_HALF_UP); if (decimal.precision() > 18) { erpOrderLog.warn(UO_LogHead + "Message: " + "refundAmount" + ": " + refundAmount + "," + decimal.precision() + ",?" + "(15,3)" + "."); erpOrderLog.warn(UO_LogHead + "Message:" + "refundAmount" + ",?????ECC."); }/*from ww w . j a va 2s .co m*/ return decimal; }
From source file:org.ojai.json.impl.JsonStreamDocumentReader.java
@Override public int getDecimalPrecision() { BigDecimal decimal = getDecimal(); if (decimal != null) { return decimal.precision(); }// w ww . j a v a2 s. c om return 0; }
From source file:org.apache.hive.hcatalog.pig.HCatBaseStorer.java
/** * Convert from Pig value object to Hive value object * This method assumes that {@link #validateSchema(org.apache.pig.impl.logicalLayer.schema.Schema.FieldSchema, org.apache.hive.hcatalog.data.schema.HCatFieldSchema, org.apache.pig.impl.logicalLayer.schema.Schema, org.apache.hive.hcatalog.data.schema.HCatSchema, int)} * which checks the types in Pig schema are compatible with target Hive table, has been called. *//*from w w w . j a v a 2 s .c o m*/ private Object getJavaObj(Object pigObj, HCatFieldSchema hcatFS) throws HCatException, BackendException { try { if (pigObj == null) return null; // The real work-horse. Spend time and energy in this method if there is // need to keep HCatStorer lean and go fast. Type type = hcatFS.getType(); switch (type) { case BINARY: return ((DataByteArray) pigObj).get(); case STRUCT: HCatSchema structSubSchema = hcatFS.getStructSubSchema(); // Unwrap the tuple. List<Object> all = ((Tuple) pigObj).getAll(); ArrayList<Object> converted = new ArrayList<Object>(all.size()); for (int i = 0; i < all.size(); i++) { converted.add(getJavaObj(all.get(i), structSubSchema.get(i))); } return converted; case ARRAY: // Unwrap the bag. DataBag pigBag = (DataBag) pigObj; HCatFieldSchema tupFS = hcatFS.getArrayElementSchema().get(0); boolean needTuple = tupFS.getType() == Type.STRUCT; List<Object> bagContents = new ArrayList<Object>((int) pigBag.size()); Iterator<Tuple> bagItr = pigBag.iterator(); while (bagItr.hasNext()) { // If there is only one element in tuple contained in bag, we throw away the tuple. bagContents.add(getJavaObj(needTuple ? bagItr.next() : bagItr.next().get(0), tupFS)); } return bagContents; case MAP: Map<?, ?> pigMap = (Map<?, ?>) pigObj; Map<Object, Object> typeMap = new HashMap<Object, Object>(); for (Entry<?, ?> entry : pigMap.entrySet()) { // the value has a schema and not a FieldSchema typeMap.put( // Schema validation enforces that the Key is a String (String) entry.getKey(), getJavaObj(entry.getValue(), hcatFS.getMapValueSchema().get(0))); } return typeMap; case STRING: case INT: case BIGINT: case FLOAT: case DOUBLE: return pigObj; case SMALLINT: if ((Integer) pigObj < Short.MIN_VALUE || (Integer) pigObj > Short.MAX_VALUE) { handleOutOfRangeValue(pigObj, hcatFS); return null; } return ((Integer) pigObj).shortValue(); case TINYINT: if ((Integer) pigObj < Byte.MIN_VALUE || (Integer) pigObj > Byte.MAX_VALUE) { handleOutOfRangeValue(pigObj, hcatFS); return null; } return ((Integer) pigObj).byteValue(); case BOOLEAN: if (pigObj instanceof String) { if (((String) pigObj).trim().compareTo("0") == 0) { return Boolean.FALSE; } if (((String) pigObj).trim().compareTo("1") == 0) { return Boolean.TRUE; } throw new BackendException("Unexpected type " + type + " for value " + pigObj + " of class " + pigObj.getClass().getName(), PigHCatUtil.PIG_EXCEPTION_CODE); } return Boolean.parseBoolean(pigObj.toString()); case DECIMAL: BigDecimal bd = (BigDecimal) pigObj; DecimalTypeInfo dti = (DecimalTypeInfo) hcatFS.getTypeInfo(); if (bd.precision() > dti.precision() || bd.scale() > dti.scale()) { handleOutOfRangeValue(pigObj, hcatFS); return null; } return HiveDecimal.create(bd); case CHAR: String charVal = (String) pigObj; CharTypeInfo cti = (CharTypeInfo) hcatFS.getTypeInfo(); if (charVal.length() > cti.getLength()) { handleOutOfRangeValue(pigObj, hcatFS); return null; } return new HiveChar(charVal, cti.getLength()); case VARCHAR: String varcharVal = (String) pigObj; VarcharTypeInfo vti = (VarcharTypeInfo) hcatFS.getTypeInfo(); if (varcharVal.length() > vti.getLength()) { handleOutOfRangeValue(pigObj, hcatFS); return null; } return new HiveVarchar(varcharVal, vti.getLength()); case TIMESTAMP: DateTime dt = (DateTime) pigObj; return new Timestamp(dt.getMillis());//getMillis() returns UTC time regardless of TZ case DATE: /** * We ignore any TZ setting on Pig value since java.sql.Date doesn't have it (in any * meaningful way). So the assumption is that if Pig value has 0 time component (midnight) * we assume it reasonably 'fits' into a Hive DATE. If time part is not 0, it's considered * out of range for target type. */ DateTime dateTime = ((DateTime) pigObj); if (dateTime.getMillisOfDay() != 0) { handleOutOfRangeValue(pigObj, hcatFS, "Time component must be 0 (midnight) in local timezone; Local TZ val='" + pigObj + "'"); return null; } /*java.sql.Date is a poorly defined API. Some (all?) SerDes call toString() on it [e.g. LazySimpleSerDe, uses LazyUtils.writePrimitiveUTF8()], which automatically adjusts for local timezone. Date.valueOf() also uses local timezone (as does Date(int,int,int). Also see PigHCatUtil#extractPigObject() for corresponding read op. This way a DATETIME from Pig, when stored into Hive and read back comes back with the same value.*/ return new Date(dateTime.getYear() - 1900, dateTime.getMonthOfYear() - 1, dateTime.getDayOfMonth()); default: throw new BackendException("Unexpected HCat type " + type + " for value " + pigObj + " of class " + pigObj.getClass().getName(), PigHCatUtil.PIG_EXCEPTION_CODE); } } catch (BackendException e) { // provide the path to the field in the error message throw new BackendException((hcatFS.getName() == null ? " " : hcatFS.getName() + ".") + e.getMessage(), e); } }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * Boost the precision by appending decimal zeros to the value. This returns a value which appears to have * a higher precision than the input./*w ww . j a v a 2s . co m*/ * * @param x The input value * @param mc The requirement on the minimum precision on return. * @return The same value as the input but with increased (pseudo) precision. */ static public BigDecimal scalePrec(final BigDecimal x, final MathContext mc) { final int diffPr = mc.getPrecision() - x.precision(); if (diffPr > 0) { return scalePrec(x, diffPr); } else { return x; } }