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

The following examples show how to use java.math.BigDecimal#stripTrailingZeros() . 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
/**
 * Return the string encoded in a BigDecimal.
 * Repeatedly multiply the input value by 65536; the integer portion after
 * such a multiplication represents a single character in base 65536.
 * Convert that back into a char and create a string out of these until we
 * have no data left.
 */
public String bigDecimalToString(BigDecimal bd) {
  BigDecimal cur = bd.stripTrailingZeros();
  StringBuilder sb = new StringBuilder();

  for (int numConverted = 0; numConverted < MAX_CHARS; numConverted++) {
    cur = cur.multiply(ONE_PLACE);
    int curCodePoint = cur.intValue();
    if (0 == curCodePoint) {
      break;
    }

    cur = cur.subtract(new BigDecimal(curCodePoint));
    sb.append(Character.toChars(curCodePoint));
  }

  return sb.toString();
}
 
Example 2
/**
 * trimBigDecimal ( (BigDecimal) a) to cut off all trailing zeros.
 * It's a terrible hack.
 * @param n the BigDecimal to trim all trailing zeros from
 * @return the trimmed BigDecimal
 */
public static BigDecimal trimBigDecimal(BigDecimal n)
{
	if (n.unscaledValue().intValue() == 0)
	{
		// Java 1.5 will not throw an ArthmeticException if you change the
		// scale of 0.0 to 0, so it will keep going through the loop below
		// forever. To get around this we test for the special case here.
		return BigDecimal.ZERO;
	}

	if (n.scale() <= 0)
	{
		return n;
	}

	BigDecimal stripped = n.stripTrailingZeros();
	if (stripped.scale() < 0)
	{
		stripped = n.setScale(0);
	}

	return stripped;
}
 
Example 3
Source Project: morf   File: ResultSetComparer.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private Comparable columnToValue(ResultSet resultSet, int columnIndex, int columnType) throws SQLException {
  if (columnTypeIsString(columnType)) {
    return resultSet.getString(columnIndex);
  } else if (columnTypeIsNumeric(columnType)) {
    BigDecimal bigDecimal = resultSet.getBigDecimal(columnIndex);
    return bigDecimal == null ? null : bigDecimal.stripTrailingZeros();
  } else if (columnTypeIsBoolean(columnType)) {
    return resultSet.getBoolean(columnIndex);
  } else if (columnTypeIsDate(columnType)) {
    return resultSet.getDate(columnIndex);
  } else {
    throw new IllegalArgumentException("Column type " + columnType + " not supported for comparison");
  }
}
 
Example 4
Source Project: jackcess   File: NumberFormatter.java    License: Apache License 2.0 5 votes vote down vote up
public String format(BigDecimal bd) {
  bd = bd.stripTrailingZeros();
  int prec = bd.precision();
  int scale = bd.scale();

  int sigDigits = prec;
  if(scale < 0) {
    sigDigits -= scale;
  } else if(scale > prec) {
    sigDigits += (scale - prec);
  }

  return ((sigDigits > _prec) ? _dfS.format(bd) : _df.format(bd));
}
 
Example 5
Source Project: parquet-mr   File: BigDecimalWritable.java    License: Apache License 2.0 5 votes vote down vote up
public void set(BigDecimal value) {
  value = value.stripTrailingZeros();
  if (value.compareTo(BigDecimal.ZERO) == 0) {
    // Special case for 0, because java doesn't strip zeros correctly on
    // that number.
    value = BigDecimal.ZERO;
  }
  set(value.unscaledValue().toByteArray(), value.scale());
}
 
Example 6
public AbstractRechnungsPositionDO setVat(final BigDecimal vat)
{
  if (vat != null) {
    this.vat = vat.stripTrailingZeros();
  } else {
    this.vat = vat;
  }
  return this;
}
 
Example 7
Source Project: jackcess   File: ValueSupport.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts the given BigDecimal to the minimal scale >= 0;
 */
static BigDecimal normalize(BigDecimal bd) {
  if(bd.scale() == 0) {
    return bd;
  }
  // handle a bug in the jdk which doesn't strip zero values
  if(bd.compareTo(BigDecimal.ZERO) == 0) {
    return BigDecimal.ZERO;
  }
  bd = bd.stripTrailingZeros();
  if(bd.scale() < 0) {
    bd = bd.setScale(0);
  }
  return bd;
}
 
Example 8
Source Project: big-math   File: BigDecimalMath.java    License: MIT License 4 votes vote down vote up
/**
	 * Rounds the specified {@link BigDecimal} to the precision of the specified {@link MathContext} including trailing zeroes.
	 *
	 * <p>This method is similar to {@link BigDecimal#round(MathContext)} but does <strong>not</strong> remove the trailing zeroes.</p>
	 *
	 * <p>Example:</p>
<pre>
MathContext mc = new MathContext(5);
System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("1.234567"), mc));    // 1.2346
System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("123.4567"), mc));    // 123.46
System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("0.001234567"), mc)); // 0.0012346
System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("1.23"), mc));        // 1.2300
System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("1.230000"), mc));    // 1.2300
System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("0.00123"), mc));     // 0.0012300
System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("0"), mc));           // 0.0000
System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("0.00000000"), mc));  // 0.0000
</pre>
	 *
	 * @param value the {@link BigDecimal} to round
	 * @param mathContext the {@link MathContext} used for the result
	 * @return the rounded {@link BigDecimal} value including trailing zeroes
	 * @see BigDecimal#round(MathContext)
     * @see BigDecimalMath#round(BigDecimal, MathContext)
	 */
	public static BigDecimal roundWithTrailingZeroes(BigDecimal value, MathContext mathContext) {
		if (value.precision() == mathContext.getPrecision()) {
			return value;
		}
		if (value.signum() == 0) {
			return BigDecimal.ZERO.setScale(mathContext.getPrecision() - 1);
		}

		try {
            BigDecimal stripped = value.stripTrailingZeros();
            int exponentStripped = exponent(stripped); // value.precision() - value.scale() - 1;

            BigDecimal zero;
            if (exponentStripped < -1) {
                zero = BigDecimal.ZERO.setScale(mathContext.getPrecision() - exponentStripped);
            } else {
                zero = BigDecimal.ZERO.setScale(mathContext.getPrecision() + exponentStripped + 1);
            }
            return stripped.add(zero, mathContext);
        } catch (ArithmeticException ex) {
		    return value.round(mathContext);
        }
	}
 
Example 9
Source Project: Time4A   File: FractionProcessor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public int print(
    ChronoDisplay formattable,
    Appendable buffer,
    AttributeQuery attributes,
    Set<ElementPosition> positions, // optional
    boolean quickPath
) throws IOException {

    BigDecimal value = toDecimal(formattable.get(this.element));
    BigDecimal min = toDecimal(formattable.getMinimum(this.element));
    BigDecimal max = toDecimal(formattable.getMaximum(this.element));

    if (value.compareTo(max) > 0) {
        value = max;
    }

    BigDecimal fraction =
        value.subtract(min).divide(
            max.subtract(min).add(BigDecimal.ONE),
            9,
            RoundingMode.FLOOR);

    fraction = (
        (fraction.compareTo(BigDecimal.ZERO) == 0)
        ? BigDecimal.ZERO
        : fraction.stripTrailingZeros()
    );

    char zeroChar = (
        quickPath
            ? this.zeroDigit
            : attributes.get(Attributes.ZERO_DIGIT, Character.valueOf('0')).charValue());

    int start = -1;
    int printed = 0;

    if (buffer instanceof CharSequence) {
        start = ((CharSequence) buffer).length();
    }

    if (fraction.scale() == 0) {
        // scale ist 0, wenn value das Minimum ist
        if (this.minDigits > 0) {
            if (this.hasDecimalSeparator()) {
                this.decimalSeparator.print(
                    formattable,
                    buffer,
                    attributes,
                    positions,
                    quickPath);
                printed++;
            }

            for (int i = 0; i < this.minDigits; i++) {
                buffer.append(zeroChar);
            }

            printed += this.minDigits;
        }
    } else {
        if (this.hasDecimalSeparator()) {
            this.decimalSeparator.print(
                formattable,
                buffer,
                attributes,
                positions,
                quickPath);
            printed++;
        }

        int outputScale =
            Math.min(
                Math.max(fraction.scale(), this.minDigits),
                this.maxDigits);
        fraction = fraction.setScale(outputScale, RoundingMode.FLOOR);
        String digits = fraction.toPlainString();
        int diff = zeroChar - '0';

        for (int i = 2, n = digits.length(); i < n; i++) {
            char c = (char) (digits.charAt(i) + diff);
            buffer.append(c);
            printed++;
        }
    }

    if (
        (start != -1)
        && (printed > 1)
        && (positions != null)
    ) {
        positions.add( // Zählung ohne Dezimaltrennzeichen
            new ElementPosition(this.element, start + 1, start + printed));
    }

    return printed;

}
 
Example 10
Source Project: ph-commons   File: MathHelper.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Get the passed BigDecimal without any trailing zeroes. Examples:
 * <ul>
 * <li>new BigDecimal ("0.00000000") --&gt; 0</li>
 * <li>new BigDecimal ("10") --&gt; 10</li>
 * <li>new BigDecimal ("10.00000000") --&gt; 10</li>
 * <li>new BigDecimal ("10.1") --&gt; 10.1</li>
 * <li>new BigDecimal ("10.10000000") --&gt; 10.1</li>
 * <li>new BigDecimal ("10.345") --&gt; 10.345</li>
 * <li>new BigDecimal ("10.3450000000") --&gt; 10.345</li>
 * </ul>
 *
 * @param aValue
 *        The BigDecimal to be modified. May be <code>null</code>.
 * @return <code>null</code> if the input value is <code>null</code>.
 */
@Nullable
@CheckReturnValue
public static BigDecimal getWithoutTrailingZeroes (@Nullable final BigDecimal aValue)
{
  if (aValue == null)
    return null;

  // stripTrailingZeros does not work for "0"!
  if (BigDecimal.ZERO.compareTo (aValue) == 0)
    return BigDecimal.ZERO;

  final BigDecimal ret = aValue.stripTrailingZeros ();
  // Avoid stuff like "6E2"
  return ret.scale () >= 0 ? ret : ret.setScale (0);
}
 
Example 11
public void setValueNumber(BigDecimal val) {
    // postgresql adds trailing zeros on jdbc read -> strip them
    this.valueNumber = val == null ? null
            // stripTrailingZeros does not work for zero, e.g. 0E-9; JDK bug 6480539
            : BigDecimal.ZERO.compareTo(val) == 0 ? BigDecimal.ZERO : val.stripTrailingZeros();
}
 
Example 12
Source Project: ripple-lib-java   File: Amount.java    License: ISC License 4 votes vote down vote up
private void setAndCheckValue(BigDecimal value) {
    this.value = value.stripTrailingZeros();
    initialize();
}
 
Example 13
Source Project: jingtum-lib-java   File: Amount.java    License: MIT 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();
}
 
Example 14
Source Project: big-math   File: BigDecimalMath.java    License: 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 15
/**
 * Converts a value for this field to a fraction between 0 and 1.
 * <p>
 * The fractional value is between 0 (inclusive) and 1 (exclusive).
 * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed.
 * The fraction is obtained by calculation from the field range using 9 decimal
 * places and a rounding mode of {@link RoundingMode#FLOOR FLOOR}.
 * The calculation is inaccurate if the values do not run continuously from smallest to largest.
 * <p>
 * For example, the second-of-minute value of 15 would be returned as 0.25,
 * assuming the standard definition of 60 seconds in a minute.
 *
 * @param value  the value to convert, must be valid for this rule
 * @return the value as a fraction within the range, from 0 to 1, not null
 * @throws DateTimeException if the value cannot be converted to a fraction
 */
private BigDecimal convertToFraction(long value) {
    ValueRange range = field.range();
    range.checkValidValue(value, field);
    BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
    BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
    BigDecimal valueBD = BigDecimal.valueOf(value).subtract(minBD);
    BigDecimal fraction = valueBD.divide(rangeBD, 9, RoundingMode.FLOOR);
    // stripTrailingZeros bug
    return fraction.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : fraction.stripTrailingZeros();
}
 
Example 16
/**
 * Converts a value for this field to a fraction between 0 and 1.
 * <p>
 * The fractional value is between 0 (inclusive) and 1 (exclusive).
 * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed.
 * The fraction is obtained by calculation from the field range using 9 decimal
 * places and a rounding mode of {@link RoundingMode#FLOOR FLOOR}.
 * The calculation is inaccurate if the values do not run continuously from smallest to largest.
 * <p>
 * For example, the second-of-minute value of 15 would be returned as 0.25,
 * assuming the standard definition of 60 seconds in a minute.
 *
 * @param value  the value to convert, must be valid for this rule
 * @return the value as a fraction within the range, from 0 to 1, not null
 * @throws DateTimeException if the value cannot be converted to a fraction
 */
private BigDecimal convertToFraction(long value) {
    ValueRange range = field.range();
    range.checkValidValue(value, field);
    BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
    BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
    BigDecimal valueBD = BigDecimal.valueOf(value).subtract(minBD);
    BigDecimal fraction = valueBD.divide(rangeBD, 9, RoundingMode.FLOOR);
    // stripTrailingZeros bug
    return fraction.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : fraction.stripTrailingZeros();
}
 
Example 17
/**
 * Converts a value for this field to a fraction between 0 and 1.
 * <p>
 * The fractional value is between 0 (inclusive) and 1 (exclusive).
 * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed.
 * The fraction is obtained by calculation from the field range using 9 decimal
 * places and a rounding mode of {@link RoundingMode#FLOOR FLOOR}.
 * The calculation is inaccurate if the values do not run continuously from smallest to largest.
 * <p>
 * For example, the second-of-minute value of 15 would be returned as 0.25,
 * assuming the standard definition of 60 seconds in a minute.
 *
 * @param value  the value to convert, must be valid for this rule
 * @return the value as a fraction within the range, from 0 to 1, not null
 * @throws DateTimeException if the value cannot be converted to a fraction
 */
private BigDecimal convertToFraction(long value) {
    ValueRange range = field.range();
    range.checkValidValue(value, field);
    BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
    BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
    BigDecimal valueBD = BigDecimal.valueOf(value).subtract(minBD);
    BigDecimal fraction = valueBD.divide(rangeBD, 9, RoundingMode.FLOOR);
    // stripTrailingZeros bug
    return fraction.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : fraction.stripTrailingZeros();
}
 
Example 18
/**
 * Converts a value for this field to a fraction between 0 and 1.
 * <p>
 * The fractional value is between 0 (inclusive) and 1 (exclusive).
 * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed.
 * The fraction is obtained by calculation from the field range using 9 decimal
 * places and a rounding mode of {@link RoundingMode#FLOOR FLOOR}.
 * The calculation is inaccurate if the values do not run continuously from smallest to largest.
 * <p>
 * For example, the second-of-minute value of 15 would be returned as 0.25,
 * assuming the standard definition of 60 seconds in a minute.
 *
 * @param value  the value to convert, must be valid for this rule
 * @return the value as a fraction within the range, from 0 to 1, not null
 * @throws DateTimeException if the value cannot be converted to a fraction
 */
private BigDecimal convertToFraction(long value) {
    ValueRange range = field.range();
    range.checkValidValue(value, field);
    BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
    BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
    BigDecimal valueBD = BigDecimal.valueOf(value).subtract(minBD);
    BigDecimal fraction = valueBD.divide(rangeBD, 9, RoundingMode.FLOOR);
    // stripTrailingZeros bug
    return fraction.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : fraction.stripTrailingZeros();
}
 
Example 19
/**
 * Converts a value for this field to a fraction between 0 and 1.
 * <p>
 * The fractional value is between 0 (inclusive) and 1 (exclusive).
 * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed.
 * The fraction is obtained by calculation from the field range using 9 decimal
 * places and a rounding mode of {@link RoundingMode#FLOOR FLOOR}.
 * The calculation is inaccurate if the values do not run continuously from smallest to largest.
 * <p>
 * For example, the second-of-minute value of 15 would be returned as 0.25,
 * assuming the standard definition of 60 seconds in a minute.
 *
 * @param value  the value to convert, must be valid for this rule
 * @return the value as a fraction within the range, from 0 to 1, not null
 * @throws DateTimeException if the value cannot be converted to a fraction
 */
private BigDecimal convertToFraction(long value) {
    ValueRange range = field.range();
    range.checkValidValue(value, field);
    BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
    BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
    BigDecimal valueBD = BigDecimal.valueOf(value).subtract(minBD);
    BigDecimal fraction = valueBD.divide(rangeBD, 9, RoundingMode.FLOOR);
    // stripTrailingZeros bug
    return fraction.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : fraction.stripTrailingZeros();
}
 
Example 20
/**
 * Converts a value for this field to a fraction between 0 and 1.
 * <p>
 * The fractional value is between 0 (inclusive) and 1 (exclusive).
 * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed.
 * The fraction is obtained by calculation from the field range using 9 decimal
 * places and a rounding mode of {@link RoundingMode#FLOOR FLOOR}.
 * The calculation is inaccurate if the values do not run continuously from smallest to largest.
 * <p>
 * For example, the second-of-minute value of 15 would be returned as 0.25,
 * assuming the standard definition of 60 seconds in a minute.
 *
 * @param value  the value to convert, must be valid for this rule
 * @return the value as a fraction within the range, from 0 to 1, not null
 * @throws DateTimeException if the value cannot be converted to a fraction
 */
private BigDecimal convertToFraction(long value) {
    ValueRange range = field.range();
    range.checkValidValue(value, field);
    BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
    BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
    BigDecimal valueBD = BigDecimal.valueOf(value).subtract(minBD);
    BigDecimal fraction = valueBD.divide(rangeBD, 9, RoundingMode.FLOOR);
    // stripTrailingZeros bug
    return fraction.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : fraction.stripTrailingZeros();
}