Java Code Examples for java.math.BigDecimal#scale()
The following examples show how to use
java.math.BigDecimal#scale() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OperatorOfNumber.java From QLExpress with Apache License 2.0 | 6 votes |
public static Number subtractPrecise(Number op1, Number op2) throws Exception { BigDecimal result = null; if(op1 instanceof BigDecimal){ if(op2 instanceof BigDecimal){ result = ((BigDecimal)op1).subtract((BigDecimal)op2); }else{ result = ((BigDecimal)op1).subtract(new BigDecimal(op2.toString())); } }else{ if(op2 instanceof BigDecimal){ result = new BigDecimal(op1.toString()).subtract((BigDecimal)op2); }else{ result = new BigDecimal(op1.toString()).subtract(new BigDecimal(op2.toString())); } } if(result.scale() ==0){ long tempLong = result.longValue(); if(tempLong <= Integer.MAX_VALUE && tempLong >= Integer.MIN_VALUE){ return (int)tempLong; }else{ return tempLong; } }else{ return result; } }
Example 2
Source File: EnumeratorUtils.java From tddl with Apache License 2.0 | 6 votes |
/** * 将BigDecimal转换为long或者double * * @param big * @return */ public static Comparable<?> toPrimaryValue(Comparable<?> comp) { if (comp instanceof BigDecimal) { BigDecimal big = (BigDecimal) comp; int scale = big.scale(); if (scale == 0) { // long int try { return big.longValueExact(); } catch (ArithmeticException e) { return big; } } else { // double float return big.doubleValue(); } } else { return comp; } }
Example 3
Source File: PFloat.java From phoenix with Apache License 2.0 | 5 votes |
@Override public Integer getScale(Object o) { if (o == null) { return null; } Float v = (Float) o; BigDecimal bd = BigDecimal.valueOf(v); return bd.scale() == 0 ? null : bd.scale(); }
Example 4
Source File: BigDecimalWrapperImpl.java From sql-layer with GNU Affero General Public License v3.0 | 5 votes |
public static int sqlPrecision(BigDecimal bd) { int precision = bd.precision(); int scale = bd.scale(); if (precision < scale) { // BigDecimal interprets something like "0.01" as having a scale of 2 and precision of 1. precision = scale; } return precision; }
Example 5
Source File: TransactionHolder.java From ETHWallet with GNU General Public License v3.0 | 5 votes |
private String getScaledValue(String valueStr, long decimals) { // Perform decimal conversion BigDecimal value = new BigDecimal(valueStr); value = value.divide(new BigDecimal(Math.pow(10, decimals))); int scale = SIGNIFICANT_FIGURES - value.precision() + value.scale(); return value.setScale(scale, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString(); }
Example 6
Source File: SQLDecimal.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
/** * Calculate the number of digits to the left of the decimal point * of the passed in value. * @param decimalValue Value to get whole digits from, never null. * @return number of whole digits. */ private static int getWholeDigits(BigDecimal decimalValue) { /** * if ONE > abs(value) then the number of whole digits is 0 */ decimalValue = decimalValue.abs(); if (ONE.compareTo(decimalValue) == 1) { return 0; } // GemStone changes BEGIN return decimalValue.precision() - decimalValue.scale(); }
Example 7
Source File: RowsAdaptor.java From database with Apache License 2.0 | 5 votes |
private BigDecimal fixBigDecimal(BigDecimal val) { if (val.scale() > 0) { val = val.stripTrailingZeros(); if (val.scale() < 0) { val = val.setScale(0); } } return val; }
Example 8
Source File: NumberConverter.java From dsl-json with BSD 3-Clause "New" or "Revised" License | 5 votes |
private static Number tryLongFromBigDecimal(final char[] buf, final int len, JsonReader reader) throws IOException { final BigDecimal num = parseNumberGeneric(buf, len, reader, false); if (num.scale() == 0 && num.precision() <= 19) { if (num.signum() == 1) { if (num.compareTo(BD_MAX_LONG) <= 0) { return num.longValue(); } } else if (num.compareTo(BD_MIN_LONG) >= 0) { return num.longValue(); } } return bigDecimalOrDouble(num, reader.unknownNumbers); }
Example 9
Source File: NumberUtil.java From phoenix with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static BigDecimal setDecimalWidthAndScale(BigDecimal decimal, int precision, int scale) { // If we could not fit all the digits before decimal point into the new desired precision and // scale, return null and the caller method should handle the error. if (((precision - scale) < (decimal.precision() - decimal.scale()))){ return null; } decimal = decimal.setScale(scale, BigDecimal.ROUND_DOWN); return decimal; }
Example 10
Source File: DecimalNormalizer.java From smarthome with Eclipse Public License 2.0 | 5 votes |
private BigDecimal stripTrailingZeros(BigDecimal value) { BigDecimal ret = new BigDecimal(value.stripTrailingZeros().toPlainString()); if (ret.scale() == 0) { ret = ret.setScale(1); } return ret; }
Example 11
Source File: TypeUtils.java From uavstack with Apache License 2.0 | 5 votes |
public static int intValue(BigDecimal decimal) { if (decimal == null) { return 0; } int scale = decimal.scale(); if (scale >= -100 && scale <= 100) { return decimal.intValue(); } return decimal.intValueExact(); }
Example 12
Source File: DecimalUtils.java From jackson-modules-java8 with Apache License 2.0 | 5 votes |
/** * Extracts the seconds and nanoseconds component of {@code seconds} as {@code long} and {@code int} * values, passing them to the given converter. The implementation avoids latency issues present * on some JRE releases. * * @since 2.9.8 */ public static <T> T extractSecondsAndNanos(BigDecimal seconds, BiFunction<Long, Integer, T> convert) { // Complexity is here to workaround unbounded latency in some BigDecimal operations. // https://github.com/FasterXML/jackson-databind/issues/2141 long secondsOnly; int nanosOnly; BigDecimal nanoseconds = seconds.scaleByPowerOfTen(9); if (nanoseconds.precision() - nanoseconds.scale() <= 0) { // There are no non-zero digits to the left of the decimal point. // This protects against very negative exponents. secondsOnly = nanosOnly = 0; } else if (seconds.scale() < -63) { // There would be no low-order bits once we chop to a long. // This protects against very positive exponents. secondsOnly = nanosOnly = 0; } else { // Now we know that seconds has reasonable scale, we can safely chop it apart. secondsOnly = seconds.longValue(); nanosOnly = nanoseconds.subtract(new BigDecimal(secondsOnly).scaleByPowerOfTen(9)).intValue(); if (secondsOnly < 0 && secondsOnly > Instant.MIN.getEpochSecond()) { // Issue #69 and Issue #120: avoid sending a negative adjustment to the Instant constructor, we want this as the actual nanos nanosOnly = Math.abs(nanosOnly); } } return convert.apply(secondsOnly, nanosOnly); }
Example 13
Source File: BigDecimalMath.java From groovy with Apache License 2.0 | 5 votes |
public Number divideImpl(Number left, Number right) { BigDecimal bigLeft = toBigDecimal(left); BigDecimal bigRight = toBigDecimal(right); try { return bigLeft.divide(bigRight); } catch (ArithmeticException e) { // set a DEFAULT precision if otherwise non-terminating int precision = Math.max(bigLeft.precision(), bigRight.precision()) + DIVISION_EXTRA_PRECISION; BigDecimal result = bigLeft.divide(bigRight, new MathContext(precision)); int scale = Math.max(Math.max(bigLeft.scale(), bigRight.scale()), DIVISION_MIN_SCALE); if (result.scale() > scale) result = result.setScale(scale, BigDecimal.ROUND_HALF_UP); return result; } }
Example 14
Source File: TypeUtils.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
public static long longValue(BigDecimal decimal) { if (decimal == null) { return 0; } int scale = decimal.scale(); if (scale >= -100 && scale <= 100) { return decimal.longValue(); } return decimal.longValueExact(); }
Example 15
Source File: TypeUtils.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
public static int intValue(BigDecimal decimal) { if (decimal == null) { return 0; } int scale = decimal.scale(); if (scale >= -100 && scale <= 100) { return decimal.intValue(); } return decimal.intValueExact(); }
Example 16
Source File: InfluxDBPersistenceService.java From openhab1-addons with Eclipse Public License 2.0 | 5 votes |
/** * This method returns an integer if possible if not a double is returned. This is an optimization * for influxdb because integers have less overhead. * * @param value the BigDecimal to be converted * @return A double if possible else a double is returned. */ private Object convertBigDecimalToNum(BigDecimal value) { Object convertedValue; if (value.scale() == 0) { logger.trace("found no fractional part"); convertedValue = value.toBigInteger(); } else { logger.trace("found fractional part"); convertedValue = value.doubleValue(); } return convertedValue; }
Example 17
Source File: DateTimeFormatterBuilder.java From hottub with GNU General Public License v2.0 | 5 votes |
@Override public boolean format(DateTimePrintContext context, StringBuilder buf) { Long value = context.getValue(field); if (value == null) { return false; } DecimalStyle decimalStyle = context.getDecimalStyle(); BigDecimal fraction = convertToFraction(value); if (fraction.scale() == 0) { // scale is zero if value is zero if (minWidth > 0) { if (decimalPoint) { buf.append(decimalStyle.getDecimalSeparator()); } for (int i = 0; i < minWidth; i++) { buf.append(decimalStyle.getZeroDigit()); } } } else { int outputScale = Math.min(Math.max(fraction.scale(), minWidth), maxWidth); fraction = fraction.setScale(outputScale, RoundingMode.FLOOR); String str = fraction.toPlainString().substring(2); str = decimalStyle.convertNumberToI18N(str); if (decimalPoint) { buf.append(decimalStyle.getDecimalSeparator()); } buf.append(str); } return true; }
Example 18
Source File: Amount.java From jingtum-lib-java with MIT License | 4 votes |
public static BigDecimal roundValue(BigDecimal value, boolean nativeSrc) { int i = value.precision() - value.scale(); return value.setScale(nativeSrc ? MAXIMUM_NATIVE_SCALE : MAXIMUM_IOU_PRECISION - i, MATH_CONTEXT.getRoundingMode()); }
Example 19
Source File: _Private_IonTextAppender.java From ion-java with Apache License 2.0 | 4 votes |
public void printDecimal(_Private_IonTextWriterBuilder _options, BigDecimal value) throws IOException { if (value == null) { appendAscii("null.decimal"); return; } BigInteger unscaled = value.unscaledValue(); int signum = value.signum(); if (signum < 0) { appendAscii('-'); unscaled = unscaled.negate(); } else if (value instanceof Decimal && ((Decimal)value).isNegativeZero()) { // for the various forms of negative zero we have to // write the sign ourselves, since neither BigInteger // nor BigDecimal recognize negative zero, but Ion does. appendAscii('-'); } final String unscaledText = unscaled.toString(); final int significantDigits = unscaledText.length(); final int scale = value.scale(); final int exponent = -scale; if (_options._decimal_as_float) { appendAscii(unscaledText); appendAscii('e'); appendAscii(Integer.toString(exponent)); } else if (exponent == 0) { appendAscii(unscaledText); appendAscii('.'); } else if (exponent < 0) { // Avoid printing small negative exponents using a heuristic // adapted from http://speleotrove.com/decimal/daconvs.html final int adjustedExponent = significantDigits - 1 - scale; if (adjustedExponent >= 0) { int wholeDigits = significantDigits - scale; appendAscii(unscaledText, 0, wholeDigits); appendAscii('.'); appendAscii(unscaledText, wholeDigits, significantDigits); } else if (adjustedExponent >= -6) { appendAscii("0."); appendAscii("00000", 0, scale - significantDigits); appendAscii(unscaledText); } else { appendAscii(unscaledText); appendAscii("d-"); appendAscii(Integer.toString(scale)); } } else // (exponent > 0) { // We cannot move the decimal point to the right, adding // rightmost zeros, because that would alter the precision. appendAscii(unscaledText); appendAscii('d'); appendAscii(Integer.toString(exponent)); } }
Example 20
Source File: Amount.java From ripple-lib-java with ISC License | 4 votes |
private static int significantDigits(BigDecimal input) { input = input.stripTrailingZeros(); return input.scale() < 0 ? input.precision() - input.scale() : input.precision(); }