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

The following examples show how to use java.math.BigDecimal#scaleByPowerOfTen() . 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: TickFactory.java    From nebula with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @param x
 * @return floor of log 10
 */
private static int log10(BigDecimal x) {
	int c = x.compareTo(BigDecimal.ONE);
	int e = 0;
	while (c < 0) {
		e--;
		x = x.scaleByPowerOfTen(1);
		c = x.compareTo(BigDecimal.ONE);
	}

	c = x.compareTo(BigDecimal.TEN);
	while (c >= 0) {
		e++;
		x = x.scaleByPowerOfTen(-1);
		c = x.compareTo(BigDecimal.TEN);
	}

	return e;
}
 
Example 2
Source File: TupleInput.java    From hypergraphdb with Apache License 2.0 6 votes vote down vote up
/**
 * Reads a sorted {@code BigDecimal}, with support for correct default 
 * sorting.
 *
 * @see <a href="package-summary.html#bigDecimalFormats">BigDecimal
 * Formats</a>
 */
public final BigDecimal readSortedBigDecimal() {    
    /* Get the sign of the BigDecimal. */
    int sign = readByte();
    
    /* Get the exponent of the BigDecimal. */
    int exponent = readSortedPackedInt();
    
    /*Get the normalized BigDecimal. */
    BigDecimal normalizedVal = readSortedNormalizedBigDecimal();
    
    /* 
     * After getting the normalized BigDecimal, we need to scale the value
     * with the exponent.
     */
    return normalizedVal.scaleByPowerOfTen(exponent * sign);
}
 
Example 3
Source File: FritzahaWebserviceUpdateNumberCallback.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void execute(int status, String response) {
    super.execute(status, response);
    if (validRequest) {
        logger.debug("Received State response " + response + " for item " + itemName);
        BigDecimal meterValue = new BigDecimal(response.trim());
        BigDecimal meterValueScaled;
        switch (type) {
            case POWER:
                meterValueScaled = meterValue.scaleByPowerOfTen(-3);
                break;
            case ENERGY:
            default:
                meterValueScaled = meterValue;
        }
        webIface.postUpdate(itemName, new DecimalType(meterValueScaled));
    }
}
 
Example 4
Source File: TickFactory.java    From nebula with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @param x
 * @param round
 *            if true, then round else take ceiling
 * @return a nice number
 */
protected static BigDecimal nicenum(BigDecimal x, boolean round) {
	int expv; /* exponent of x */
	double f; /* fractional part of x */
	double nf; /* nice, rounded number */
	BigDecimal bf;

	boolean negative = x.signum() == -1;
	x = x.abs();
	expv = log10(x);
	bf = x.scaleByPowerOfTen(-expv);
	f = bf.doubleValue(); /* between 1 and 10 */
	if (round) {
		if (f < 1.5)
			nf = 1;
		else if (f < 2.25)
			nf = 2;
		else if (f < 3.25)
			nf = 2.5;
		else if (f < 7.5)
			nf = 5;
		else
			nf = 10;
	} else if (f <= 1.)
		nf = 1;
	else if (f <= 2.)
		nf = 2;
	else if (f <= 5.)
		nf = 5;
	else
		nf = 10;

	if (negative) {
		nf = -nf;
	}
	return BigDecimal.valueOf(nf).scaleByPowerOfTen(expv).stripTrailingZeros();
}
 
Example 5
Source File: DecimalConstructor.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private static BigDecimal constructFrom128(long high, long low)
{
    int sign = ((high & 0x8000000000000000l) == 0) ? 1 : -1;

    int exponent = 0;
    long significand = high;

    if((high & 0x6000000000000000l) != 0x6000000000000000l)
    {
        exponent = ((int) ((high & 0x7FFE000000000000l) >> 49)) - 6176;
        significand = high & 0x0001ffffffffffffl;
    }
    else if((high &  0x7800000000000000l) != 0x7800000000000000l)
    {
        exponent = ((int)((high & 0x1fff800000000000l)>>47)) - 6176;
        significand = (0x00007fffffffffffl & high) | 0x0004000000000000l;
    }
    else
    {
        // NaN or infinite
        return null;
    }


    BigDecimal bigDecimal = new BigDecimal(significand).multiply(TWO_TO_THE_SIXTY_FOUR);
    if(low >=0)
    {
        bigDecimal = bigDecimal.add(new BigDecimal(low));
    }
    else
    {
        bigDecimal = bigDecimal.add(TWO_TO_THE_SIXTY_FOUR.add(new BigDecimal(low)));
    }
    if(((high & 0x8000000000000000l) != 0))
    {
        bigDecimal = bigDecimal.negate();
    }
    bigDecimal = bigDecimal.scaleByPowerOfTen(exponent);
    return bigDecimal;
}
 
Example 6
Source File: DecimalConstructor.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private static BigDecimal constructFrom64(final long val)
{
    int sign = ((val & 0x8000000000000000l) == 0) ? 1 : -1;

    int exponent = 0;
    long significand = val;

    if((val & 0x6000000000000000l) != 0x6000000000000000l)
    {
        exponent = ((int) ((val & 0x7FE0000000000000l) >> 53)) - 398;
        significand = val & 0x001fffffffffffffl;
    }
    else if((val &  0x7800000000000000l) != 0x7800000000000000l)
    {
        exponent = ((int)((val & 0x1ff8000000000000l)>>51)) - 398;
        significand = (0x0007ffffffffffffl & val) | 0x0020000000000000l;
    }
    else
    {
        // NaN or infinite
        return null;
    }

    BigDecimal bigDecimal = new BigDecimal(sign * significand);
    bigDecimal = bigDecimal.scaleByPowerOfTen(exponent);
    return bigDecimal;
}
 
Example 7
Source File: DecimalConstructor.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private static BigDecimal constructFrom32(final int val)
{
    int sign = ((val & 0x80000000) == 0) ? 1 : -1;

    int exponent = 0;
    int significand = val;

    if((val & 0x60000000) != 0x60000000)
    {
        exponent = ((val & 0x7F800000) >> 23) - 101;
        significand = val & 0x007fffffff;
    }
    else if((val &  0x78000000) != 0x78000000)
    {
        exponent = ((val & 0x1fe00000)>>21) - 101;
        significand = (0x001fffff & val) | 0x00800000;
    }
    else
    {
        // NaN or infinite
        return null;
    }

    BigDecimal bigDecimal = new BigDecimal(sign * significand);
    bigDecimal = bigDecimal.scaleByPowerOfTen(exponent);
    return bigDecimal;
}
 
Example 8
Source File: DecimalUtils.java    From jackson-modules-java8 with Apache License 2.0 5 votes vote down vote up
/**
 * 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 9
Source File: BigDecimalConvertTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * scaleByPowerOfTen(int n)
 */
public void testScaleByPowerOfTen1() {
    String a = "1231212478987482988429808779810457634781384756794987";
    int aScale = 13;
    BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale);
    BigDecimal result = aNumber.scaleByPowerOfTen(10);
    String res = "1231212478987482988429808779810457634781384756794.987";
    int resScale = 3;
    assertEquals("incorrect value", res, result.toString());
    assertEquals("incorrect scale", resScale, result.scale());
}
 
Example 10
Source File: BigDecimalConvertTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * scaleByPowerOfTen(int n)
 */
public void testScaleByPowerOfTen2() {
    String a = "1231212478987482988429808779810457634781384756794987";
    int aScale = -13;
    BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale);
    BigDecimal result = aNumber.scaleByPowerOfTen(10);
    String res = "1.231212478987482988429808779810457634781384756794987E+74";
    int resScale = -23;
    assertEquals("incorrect value", res, result.toString());
    assertEquals("incorrect scale", resScale, result.scale());
}
 
Example 11
Source File: DecimalConverter.java    From atdl4j with MIT License 5 votes vote down vote up
@Override
public Object convertControlValueToParameterValue(Object aValue)
{
	BigDecimal tempBigDecimal = DatatypeConverter.convertValueToBigDecimalDatatype( aValue );
	if ( ( tempBigDecimal != null ) && ( isControlMultiplyBy100() ) )
	{
		// -- divide Control's value by 100 --
		return tempBigDecimal.scaleByPowerOfTen( -2 );
	}
	else
	{
		// -- aDatatypeIfNull=DATATYPE_BIG_DECIMAL --
		return DatatypeConverter.convertValueToDatatype( tempBigDecimal, getParameterDatatype( BigDecimal.class ) );
	}
}
 
Example 12
Source File: DecimalConverter.java    From atdl4j with MIT License 5 votes vote down vote up
@Override
public BigDecimal convertParameterValueToControlValue(Object aValue)
{
	BigDecimal tempBigDecimal = DatatypeConverter.convertValueToBigDecimalDatatype( aValue );
	
	if ( ( tempBigDecimal != null ) && ( isControlMultiplyBy100() ) )
	{
		// -- multiply Control's value by 100 --
		return tempBigDecimal.scaleByPowerOfTen( 2 );
	}
	else
	{	
		return tempBigDecimal;
	}
}
 
Example 13
Source File: DecimalConverter.java    From atdl4j with MIT License 5 votes vote down vote up
@Override
public String convertParameterValueToFixWireValue(Object aParameterValue)
{
	BigDecimal tempBigDecimal = convertParameterValueToParameterComparable( aParameterValue );
	
	if ( ( tempBigDecimal != null ) && ( isParameterMultiplyBy100() ) )
	{
		// -- multiply the parameter value x100 for its wire value --
		tempBigDecimal = tempBigDecimal.scaleByPowerOfTen( 2 );
	}
	
	return toString( tempBigDecimal, getPrecision() );
}
 
Example 14
Source File: StringConverter.java    From atdl4j with MIT License 5 votes vote down vote up
@Override
public Object convertControlValueToParameterValue(Object aValue)
{
	// -- handle PercentageT getParameter() coming through as String (eg minValue, maxValue) --
	if ( ( aValue != null ) && ( isControlMultiplyBy100() ) )
	{
		BigDecimal tempBigDecimal;
		try
		{
			tempBigDecimal = DatatypeConverter.convertValueToBigDecimalDatatype( aValue );
		}
		catch (NumberFormatException e)
		{
			throw new NumberFormatException( "Invalid Decimal Number Format: [" + aValue + "] for Parameter: " + getParameterName() );
		}

		// -- Divide Control's value by 100 --
		tempBigDecimal = tempBigDecimal.scaleByPowerOfTen( -2 );
		
		return tempBigDecimal;
	}
	else
	{
		// -- aDatatypeIfNull=DatatypeConverter.DATATYPE_STRING --
		return DatatypeConverter.convertValueToDatatype( aValue, getParameterDatatype( String.class ) );
	}
}
 
Example 15
Source File: ArithmeticHelper.java    From exchange-gateway-rest with Apache License 2.0 4 votes vote down vote up
public static BigDecimal toBaseUnits(BigDecimal price, GatewayAssetSpec assetSpec) {
    return price.scaleByPowerOfTen(assetSpec.scale);
}
 
Example 16
Source File: ResultUtil.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
/**
 * Convert a SFTimestamp to a string value.
 *
 * @param sfTS                  snowflake timestamp object
 * @param columnType            internal snowflake t
 * @param scale                 timestamp scale
 * @param timestampNTZFormatter snowflake timestamp ntz format
 * @param timestampLTZFormatter snowflake timestamp ltz format
 * @param timestampTZFormatter  snowflake timestamp tz format
 * @param session               session object
 * @return timestamp in string in desired format
 * @throws SFException timestamp format is missing
 */
static public String getSFTimestampAsString(
    SFTimestamp sfTS, int columnType, int scale,
    SnowflakeDateTimeFormat timestampNTZFormatter,
    SnowflakeDateTimeFormat timestampLTZFormatter,
    SnowflakeDateTimeFormat timestampTZFormatter,
    SFSession session) throws SFException
{
  // Derive the timestamp formatter to use
  SnowflakeDateTimeFormat formatter;
  if (columnType == Types.TIMESTAMP)
  {
    formatter = timestampNTZFormatter;
  }
  else if (columnType == SnowflakeUtil.EXTRA_TYPES_TIMESTAMP_LTZ)
  {
    formatter = timestampLTZFormatter;
  }
  else // TZ
  {
    formatter = timestampTZFormatter;
  }

  if (formatter == null)
  {
    throw (SFException) IncidentUtil.generateIncidentV2WithException(
        session,
        new SFException(ErrorCode.INTERNAL_ERROR,
                        "missing timestamp formatter"),
        null,
        null);
  }

  try
  {
    Timestamp adjustedTimestamp =
        ResultUtil.adjustTimestamp(sfTS.getTimestamp());

    return formatter.format(
        adjustedTimestamp, sfTS.getTimeZone(), scale);
  }
  catch (SFTimestamp.TimestampOperationNotAvailableException e)
  {
    // this timestamp doesn't fit into a Java timestamp, and therefore we
    // can't format it (for now). Just print it out as seconds since epoch.

    BigDecimal nanosSinceEpoch = sfTS.getNanosSinceEpoch();

    BigDecimal secondsSinceEpoch = nanosSinceEpoch.scaleByPowerOfTen(-9);

    return secondsSinceEpoch.setScale(scale).toPlainString();
  }
}