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

The following examples show how to use java.math.BigDecimal#precision() . 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: Round.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
@Override
public Object compute(Object[] args, ExecutionContext ec) {
    DataType type = getReturnType();
    if (ExecUtils.isNull(args[0])) {
        return null;
    }

    BigDecimal d = DataType.BigDecimalType.convertFrom(args[0]);
    int x = 0;
    if (args.length >= 2 && !ExecUtils.isNull(args[1])) {
        x = DataType.IntegerType.convertFrom(args[1]);
    }

    if (x >= 0) {
        int precision = d.precision() - d.scale() + x;
        if (precision < 0) {
            d = BigDecimal.ZERO;
        } else {
            d = d.round(new MathContext(precision, RoundingMode.HALF_UP));
        }
    } else {
        x = Math.abs(x);
        d = d.movePointLeft(x).setScale(0, RoundingMode.HALF_UP).multiply(new BigDecimal(10).pow(x));
    }
    return type.convertFrom(d);
}
 
Example 2
Source File: CDecimalField.java    From Open-Lowcode with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean isRestrictionValid(String restriction) {
	if (restriction == null)
		return true;
	try {
		BigDecimal bigdecimal = new BigDecimal(restriction);
		int entryprecision = bigdecimal.precision();
		int entryscale = bigdecimal.scale();
		if ((entryprecision - entryscale) > (precision - scale))
			return false;
		if (entryscale > scale)
			return false;
	} catch (NumberFormatException e) {
		return false;
	}
	return true;
}
 
Example 3
Source File: DecimalDataObjectField.java    From Open-Lowcode with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * cheks that the BigDecimal is compliant with format, and if so, sets the new
 * value to the provided input
 * 
 * @param value candidate for new value
 */
public void setValue(BigDecimal value) {
	BigDecimal cleanvalue = cleanBigDecimal(value, definition.getScale());
	if (cleanvalue != null)
		if (cleanvalue.precision() > this.definition.getPrecision())
			throw new RuntimeException(String.format(
					"field %s : incorrect precision of decimal provided, expected %d decimal, got '%d' (%d char)",
					this.definition.getName(), this.definition.getPrecision(), cleanvalue, cleanvalue.precision()));
	if (cleanvalue != null)
		if (cleanvalue.scale() > this.definition.getScale())
			throw new RuntimeException(String.format(
					"field %s : incorrect length of decimal provided, expected %d decimal, got '%d' (%d char)",
					this.definition.getName(), this.definition.getScale(), cleanvalue, cleanvalue.scale()));

	this.decimalfield.setPayload(cleanvalue);

}
 
Example 4
Source File: DigitsPropertyValidator.java    From dolphin-platform with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean checkValid(final CharSequence charSequence, final ConstraintValidatorContext context) {
	//null values are valid
    if ( charSequence == null ) {
        return true;
    }

    final BigDecimal bigNum = getBigDecimalValue( charSequence );
    if ( bigNum == null ) {
        return false;
    }

    final int integerPartLength = bigNum.precision() - bigNum.scale();
    final int fractionPartLength = bigNum.scale() < 0 ? 0 : bigNum.scale();

    return ( maxIntegerLength >= integerPartLength && maxFractionLength >= fractionPartLength );

}
 
Example 5
Source File: TransactionDetailActivity.java    From trust-wallet-android-source with GNU General Public License v3.0 5 votes vote down vote up
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 = 3 - 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 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 7
Source File: Utils.java    From rmlmapper-java with MIT License 5 votes vote down vote up
private static String formatToScientific(Double d) {
    BigDecimal input = BigDecimal.valueOf(d).stripTrailingZeros();
    int precision = input.scale() < 0
            ? input.precision() - input.scale()
            : input.precision();
    StringBuilder s = new StringBuilder("0.0");
    for (int i = 2; i < precision; i++) {
        s.append("#");
    }
    s.append("E0");
    NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
    DecimalFormat df = (DecimalFormat) nf;
    df.applyPattern(s.toString());
    return df.format(d);
}
 
Example 8
Source File: BigIntegerConstraint.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isDigits(int integer, int fraction) {
    BigDecimal bigDecimal = new BigDecimal(value).stripTrailingZeros();

    int integerLength = bigDecimal.precision() - bigDecimal.scale();
    int fractionLength = bigDecimal.scale() < 0 ? 0 : bigDecimal.scale();

    return integer >= integerLength && fraction >= fractionLength;
}
 
Example 9
Source File: BigDecimalFormatValidator.java    From Open-Lowcode with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public String valid(String valueasstring) {

	if (valueasstring.length() > 0) {

		try {
			String newvaluecleaned = valueasstring.replaceAll("\\s+", "");
			if (valueasstring.equals("-"))
				return ("-");
			boolean hasdotatend = false;
			String dotsandzerosatend = null;
			String zerosatend = null;
			if (newvaluecleaned.length() > 0)
				if (newvaluecleaned.charAt(newvaluecleaned.length() - 1) == '.') {
					hasdotatend = true;
					newvaluecleaned = newvaluecleaned.substring(0, newvaluecleaned.length() - 1);
				}
			dotsandzerosatend = finishesbydotandzero(newvaluecleaned);
			zerosatend = finishesbyzerosafterdecimal(newvaluecleaned);
			BigDecimal bigdecimal = new BigDecimal(newvaluecleaned);
			int entryprecision = bigdecimal.precision();
			int entryscale = bigdecimal.scale();
			if ((entryprecision - entryscale) > (precision - scale))
				return null;
			if (entryscale > scale)
				return null;
			return formatfordecimal.format(bigdecimal) + (hasdotatend ? "." : "")
					+ (dotsandzerosatend != null ? dotsandzerosatend : "") + (zerosatend != null ? zerosatend : "");
		} catch (NumberFormatException e) {
			return null;
		}
	}
	return valueasstring;
}
 
Example 10
Source File: TransactionHolder.java    From ETHWallet with GNU General Public License v3.0 5 votes vote down vote up
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 11
Source File: AbstractTestDecimalAverageAggregation.java    From presto with Apache License 2.0 5 votes vote down vote up
@Override
protected SqlDecimal getExpectedValue(int start, int length)
{
    if (length == 0) {
        return null;
    }
    BigDecimal avg = BigDecimal.ZERO;
    for (int i = start; i < start + length; i++) {
        avg = avg.add(getBigDecimalForCounter(i));
    }
    avg = avg.divide(BigDecimal.valueOf(length), ROUND_HALF_UP);
    return new SqlDecimal(avg.unscaledValue(), avg.precision(), avg.scale());
}
 
Example 12
Source File: HumanValueFormatter.java    From disthene-reader with MIT License 5 votes vote down vote up
@Override
protected String formatDoubleSpecialSmart(Double value) {
    BigDecimal bigDecimal = BigDecimal.valueOf(value);

    // do not do this for math integers
    if (!DoubleMath.isMathematicalInteger(value)) {
        // precision is just like in graphite (scale check redundant but let it be)
        if (bigDecimal.precision() > 12 && bigDecimal.scale() > 0) {
            int roundTo = bigDecimal.scale() - bigDecimal.precision() + 12 > 0 ? bigDecimal.scale() - bigDecimal.precision() + 12 : 0;
            bigDecimal = bigDecimal.setScale(roundTo, BigDecimal.ROUND_HALF_UP);
        }
    }

    return formatter.format(bigDecimal.doubleValue());
}
 
Example 13
Source File: LmdbDataOutput.java    From hypergraphdb with Apache License 2.0 4 votes vote down vote up
/**
 * Writes a normalized {@code BigDecimal}.
 */
private final HGDataOutput writeSortedNormalizedBigDecimal(BigDecimal val) {
	/*
	 * The byte format for a sorted normalized {@code BigDecimal} value is: Byte 0 ~ N: Store all digits with
	 * sign. Each 9 digits is regarded as one integer, and written as a SortedPackedInteger value. If there
	 * are not enough 9 digits, pad trailing zeros. Since we may pad trailing zeros for serialization, when
	 * doing de-serialization, we need to delete the trailing zeros. In order to designate a special value as
	 * the terminator byte, we set val = (val < 0) ? (val - 1) : val. Byte N + 1: Terminator byte. The
	 * terminator byte is -1, and written as a SortedPackedInteger value.
	 */

	/* get the precision, scale and sign of the BigDecimal. */
	int precision = val.precision();
	int scale = val.scale();
	int sign = val.signum();

	/* Start the serialization of the whole digits. */
	String digitsStr = val.abs().toPlainString();

	/*
	 * The default capacity of a StringBuilder is 16 chars, which is enough to hold a group of digits having 9
	 * digits.
	 */
	StringBuilder groupDigits = new StringBuilder();
	for (int i = 0; i < digitsStr.length();) {
		char digit = digitsStr.charAt(i++);

		/* Ignore the decimal. */
		if (digit != '.') {
			groupDigits.append(digit);
		}

		/*
		 * For the last group of the digits, if there are not 9 digits, pad trailing zeros.
		 */
		if (i == digitsStr.length() && groupDigits.length() < 9) {
			final int insertLen = 9 - groupDigits.length();
			for (int k = 0; k < insertLen; k++) {
				groupDigits.append("0");
			}
		}

		/* Group every 9 digits as an Integer. */
		if (groupDigits.length() == 9) {
			int subVal = Integer.valueOf(groupDigits.toString());
			if (sign < 0) {
				subVal = -subVal;
			}

			/*
			 * Reset the sub-value, so the value -1 will be designated as the terminator byte.
			 */
			subVal = subVal < 0 ? subVal - 1 : subVal;
			writeSortedPackedInt(subVal);
			groupDigits.setLength(0);
		}
	}

	/* Write the terminator byte. */
	writeSortedPackedInt(-1);
	return this;
}
 
Example 14
Source File: Amount.java    From RipplePower with Apache License 2.0 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 15
Source File: SqlDecimal.java    From presto with Apache License 2.0 4 votes vote down vote up
public static SqlDecimal of(String decimalValue)
{
    BigDecimal bigDecimal = new BigDecimal(decimalValue);
    return new SqlDecimal(bigDecimal.unscaledValue(), bigDecimal.precision(), bigDecimal.scale());
}
 
Example 16
Source File: DigitNumberArithmetic.java    From chart-fx with Apache License 2.0 4 votes vote down vote up
public static int getNumberOfSignificantDigits(final double val) {
    BigDecimal input = BigDecimal.valueOf(val);
    input = input.stripTrailingZeros();
    return input.scale() < 0 ? input.precision() - input.scale() : input.precision();
}
 
Example 17
Source File: ValueExpressions.java    From Bats with Apache License 2.0 4 votes vote down vote up
public Decimal18Expression(BigDecimal input, ExpressionPosition pos) {
  super(pos);
  this.scale = input.scale();
  this.precision = input.precision();
  this.decimal = input.setScale(scale, BigDecimal.ROUND_HALF_UP).longValue();
}
 
Example 18
Source File: PriceConverter.java    From development with Apache License 2.0 4 votes vote down vote up
/**
 * Parses a price of type <code>String</code> and converts it to a
 * <code>BigDecimal</code>, considering the active locale. It accepts
 * maximum {@link #NUMBER_OF_INTEGER_PLACES} integer digits and
 * {@link #NUMBER_OF_DECIMAL_PLACES} decimal digits. It accepts grouping
 * separators according to the active locale, placed at any position in the
 * integer part, but not in the decimal part. It accepts no <code>+</code>
 * symbol and no currency symbols (like <code>€</code> or <code>$</code>).
 * Also, If <code>allosNegativePrice</code> is <code>true</code>, negative
 * price is not accepted.
 * 
 * @param price
 *            The price to be parsed as <code>String</code>. May be
 *            <code>null</code>, otherwise it will be trimmed.
 * @param allosNegativePrice
 *            Defined if negative price value is allowed or not. If value is
 *            <code>true</code>, negative price is not accepted.
 * @return The parsed <code>BigDecimal</code> representing the
 *         <code>price</code>. Returns <code>BigDecimal.ZERO</code> if the
 *         given <code>price</code> parameter is <code>null</code> or it
 *         contains no characters other then blanks.
 * @throws ParseException
 *             if the specified <code>price</code> string represents no
 *             valid price as described.
 */
public BigDecimal parse(String price, boolean allowNegativePrice)
        throws ParseException {
    if (price == null || price.trim().length() == 0) {
        return BigDecimal.ZERO;
    }
    BigDecimal bigDecimal = VALIDATOR.validate(price,
            FORMAT_PATTERN_WITH_GROUPING, getActiveLocale());
    if (bigDecimal == null) {
        throw new ParseException("Invalid price: " + price, 0);
    } else if (bigDecimal.compareTo(BigDecimal.ZERO) < 0
            && !allowNegativePrice) {
        // used compareTo() to ignore the scale
        throw new ParseException("Negative price: " + price, 0);
    }
    if (bigDecimal.scale() > NUMBER_OF_DECIMAL_PLACES
            || (bigDecimal.precision() - bigDecimal.scale()) > NUMBER_OF_INTEGER_PLACES) {
        throw new ParseException(
                "ERROR_PRICEMODEL_INVALID_FRACTIONAL_PART", 0);
    }
    return bigDecimal;
}
 
Example 19
Source File: BigDecimalMath.java    From big-math with MIT License 3 votes vote down vote up
/**
 * Returns the number of significant digits of the specified {@link BigDecimal}.
 *
 * <p>The result contains the number of all digits before the decimal point and
 * all digits after the decimal point excluding trailing zeroes.</p>
 *
 * <p>Examples:</p>
 * <ul>
 * <li><code>significantDigits(new BigDecimal("12300.00"))</code> returns 5</li>
 * <li><code>significantDigits(new BigDecimal("1.23000"))</code> returns 3</li>
 * <li><code>significantDigits(new BigDecimal("0.00012300"))</code> returns 3</li>
 * <li><code>significantDigits(new BigDecimal("12300.4500"))</code> returns 7</li>
 * </ul>
 *
 * <p>See: <a href="https://en.wikipedia.org/wiki/Significant_figures">Wikipedia: Significant figures</a></p>
 *
 * @param value the {@link BigDecimal}
 * @return the number of significant digits
 * @see BigDecimal#stripTrailingZeros()
 * @see BigDecimal#precision()
 */
public static int significantDigits(BigDecimal value) {
	BigDecimal stripped = value.stripTrailingZeros();
	if (stripped.scale() >= 0) {
		return stripped.precision();
	} else {
		return stripped.precision() - stripped.scale();
	}
}
 
Example 20
Source File: RoundFloorCeilExpressionsTest.java    From phoenix with Apache License 2.0 3 votes vote down vote up
/**
 * Produces the smallest unit of difference possible for the given decimal that will still
 * be serialized accurately. For example, if the MAXIMUM_RELIABLE_PRECISION were 4, then
 * getSmallestUnit(2.3) would produce 0.001, as 2.301 could be serialized accurately but
 * 2.3001 could not.
 * @param decimal  the decimal to find the smallest unit in relation to
 * @return  the smallest BigDecimal unit possible to add to decimal while still maintaining
 *          accurate serialization
 * @throws IllegalArgumentException if decimal requires more than the maximum reliable precision
 */
private static BigDecimal getSmallestUnit(BigDecimal decimal) {
    if (decimal.precision() > PDataType.MAX_PRECISION) {
        throw new IllegalArgumentException("rounding errors mean that we cannot reliably test " + decimal);
    }
    int minScale = decimal.scale() + (PDataType.MAX_PRECISION - decimal.precision());
    return BigDecimal.valueOf(1, minScale);
}