Java Code Examples for java.math.BigDecimal#scale()

The following examples show how to use java.math.BigDecimal#scale() . These examples are extracted from open source projects. 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 Project: QLExpress   File: OperatorOfNumber.java    License: Apache License 2.0 6 votes vote down vote up
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 Project: tddl   File: EnumeratorUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 将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 Project: uavstack   File: TypeUtils.java    License: Apache License 2.0 5 votes vote down vote up
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 4
@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 5
/**
 * 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 6
Source Project: grpc-nebula-java   File: TypeUtils.java    License: Apache License 2.0 5 votes vote down vote up
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 7
Source Project: grpc-nebula-java   File: TypeUtils.java    License: Apache License 2.0 5 votes vote down vote up
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 8
Source Project: groovy   File: BigDecimalMath.java    License: Apache License 2.0 5 votes vote down vote up
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 9
/**
 * 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 10
Source Project: phoenix   File: PFloat.java    License: Apache License 2.0 5 votes vote down vote up
@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 11
private BigDecimal stripTrailingZeros(BigDecimal value) {
    BigDecimal ret = new BigDecimal(value.stripTrailingZeros().toPlainString());
    if (ret.scale() == 0) {
        ret = ret.setScale(1);
    }
    return ret;
}
 
Example 12
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 13
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 14
Source Project: database   File: RowsAdaptor.java    License: Apache License 2.0 5 votes vote down vote up
private BigDecimal fixBigDecimal(BigDecimal val) {
  if (val.scale() > 0) {
    val = val.stripTrailingZeros();
    if (val.scale() < 0) {
      val = val.setScale(0);
    }
  }
  return val;
}
 
Example 15
Source Project: gemfirexd-oss   File: SQLDecimal.java    License: Apache License 2.0 5 votes vote down vote up
/**
	 * 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 16
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 17
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 18
Source Project: jingtum-lib-java   File: Amount.java    License: MIT License 4 votes vote down vote up
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
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 Project: ripple-lib-java   File: Amount.java    License: ISC License 4 votes vote down vote up
private static int significantDigits(BigDecimal input) {
    input = input.stripTrailingZeros();
    return input.scale() < 0
            ? input.precision() - input.scale()
            : input.precision();
}