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

The following examples show how to use java.math.BigDecimal#toBigInteger() . 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: StockPriceHistoryImpl.java    From training with MIT License 6 votes vote down vote up
private BigDecimal sqrt(BigDecimal bd) {
    BigInteger bi = bd.toBigInteger();
    int length = bi.toString().length();
    if ((length % 2) == 0) {
        length--;
    }
    length /= 2;
    BigDecimal initial = BigDecimal.ONE.movePointRight(length);
    BigDecimal last;
    do {
        last = initial;
        initial = bd.divide(initial);
        initial = initial.add(last);
        initial = initial.divide(TWO);
    } while (bd.subtract(initial.multiply(initial)).
                abs().compareTo(BigDecimal.ONE) == 0);
    return initial;
}
 
Example 2
Source File: TrovitUtils.java    From OpenEstate-IO with Apache License 2.0 6 votes vote down vote up
/**
 * Write a {@link BigDecimal} value into XML output for a room number.
 *
 * @param value value to write
 * @return XML string
 * @throws IllegalArgumentException if a validation error occurred
 */
public static String printRoomsValue(BigDecimal value) {
    if (value == null)
        throw new IllegalArgumentException("Can't print empty rooms value!");
    if (value.compareTo(BigDecimal.ZERO) < 0)
        throw new IllegalArgumentException("Can't print rooms value '" + value + "' because it is below 0!");
    if (value.compareTo(new BigDecimal("20")) > 0)
        throw new IllegalArgumentException("Can't print rooms value '" + value + "' because it is above 20!");

    value = value.setScale(1, BigDecimal.ROUND_HALF_UP);
    //return DatatypeConverter.printDecimal( value );

    final BigInteger integerPart = value.toBigInteger();
    final BigInteger decimalPart = value.subtract(new BigDecimal(integerPart, 1)).multiply(BigDecimal.TEN).toBigInteger();
    if (decimalPart.compareTo(BigInteger.ZERO) != 0)
        return integerPart.toString() + ".5";

    return DatatypeConverter.printInteger(integerPart);
}
 
Example 3
Source File: StockPriceHistoryExternalizable.java    From training with MIT License 6 votes vote down vote up
private BigDecimal sqrt(BigDecimal bd) {
    BigInteger bi = bd.toBigInteger();
    int length = bi.toString().length();
    if ((length % 2) == 0) {
        length--;
    }
    length /= 2;
    BigDecimal initial = BigDecimal.ONE.movePointRight(length);
    BigDecimal last;
    do {
        last = initial;
        initial = bd.divide(initial);
        initial = initial.add(last);
        initial = initial.divide(TWO);
    } while (bd.subtract(initial.multiply(initial)).
                         abs().compareTo(BigDecimal.ONE) == 0);
    return initial;
}
 
Example 4
Source File: ExpressionEvaluator.java    From doma with Apache License 2.0 6 votes vote down vote up
protected Object narrowValue(BigDecimal value, Class<?> clazz) {
  if (clazz == BigDecimal.class) {
    return value;
  } else if (clazz == BigInteger.class) {
    return value.toBigInteger();
  } else if (clazz == Double.class || clazz == double.class) {
    return value.doubleValue();
  } else if (clazz == Float.class || clazz == float.class) {
    return value.floatValue();
  } else if (clazz == Long.class || clazz == long.class) {
    return value.longValue();
  } else if (clazz == Integer.class || clazz == int.class) {
    return value.intValue();
  } else if (clazz == Short.class || clazz == short.class) {
    return value.shortValue();
  } else if (clazz == Byte.class || clazz == byte.class) {
    return value.byteValue();
  }
  return assertUnreachable();
}
 
Example 5
Source File: InfluxDBPersistenceService.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 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 File: JdbcValueGetters.java    From dekaf with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
BigInteger getValue(@NotNull final ResultSet rset, final int index) throws SQLException {
  BigDecimal bd = rset.getBigDecimal(index);
  if (rset.wasNull()) return null;
  return bd.toBigInteger();
}
 
Example 7
Source File: BigDecimalConvertTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a positive BigDecimal to BigInteger
 */
public void testToBigIntegerPos3() {
    String a = "123809648392384754573567356745735.63567890295784902768787678287E+45";
    BigInteger bNumber = new BigInteger("123809648392384754573567356745735635678902957849027687876782870000000000000000");
    BigDecimal aNumber = new BigDecimal(a);
    BigInteger result = aNumber.toBigInteger();
    assertTrue("incorrect value", result.equals(bNumber));
}
 
Example 8
Source File: JrsNumber.java    From jackson-jr with Apache License 2.0 5 votes vote down vote up
public BigInteger asBigInteger() throws IOException {
    if (_value instanceof BigInteger) {
        return (BigInteger) _value;
    }
    if (_value instanceof BigDecimal) {
        BigDecimal dec = (BigDecimal) _value;
        return dec.toBigInteger();
    }
    return BigInteger.valueOf(_value.longValue());
}
 
Example 9
Source File: ItemDecimalTypeCast.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public BigInteger valInt() {
    BigDecimal tmp = valDecimal();
    if (nullValue)
        return BigInteger.ZERO;
    return tmp.toBigInteger();
}
 
Example 10
Source File: BigDecimalConvertTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a positive BigDecimal to BigInteger
 */
public void testToBigIntegerPos1() {
    String a = "123809648392384754573567356745735.63567890295784902768787678287E+21";
    BigInteger bNumber = new BigInteger("123809648392384754573567356745735635678902957849027687");
    BigDecimal aNumber = new BigDecimal(a);
    BigInteger result = aNumber.toBigInteger();
    assertTrue("incorrect value", result.equals(bNumber));
}
 
Example 11
Source File: ZdrProcedures.java    From ongdb-lab-apoc with Apache License 2.0 5 votes vote down vote up
/**
 * @param
 * @return
 * @Description: TODO(小数点向后移动)
 */
@UserFunction(name = "zdr.apoc.moveDecimalPoint")
@Description("Move six decimal points")
public Number moveDecimalPoint(@Name("mapPara") Map<String, Object> mapPara) {
    double scoreObject = shiftDouble(mapPara.get("scoreObject"));
    double moveLength = shiftDouble(mapPara.get("moveLength"));
    BigDecimal score = BigDecimal.valueOf(scoreObject);
    score = score.multiply(BigDecimal.valueOf(moveLength));
    BigInteger scoreInt = score.toBigInteger();
    return scoreInt.intValue();
}
 
Example 12
Source File: MarkerSetImpl.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private BigInteger getIndex(BigInteger bigStarty, BigDecimal bigHeight, BigInteger numIndexes,
		BigInteger numIndexesMinus1) {
	BigDecimal total = new BigDecimal(bigStarty.multiply(numIndexes));
	BigDecimal div = total.divideToIntegralValue(bigHeight);
	BigInteger index = div.toBigInteger();

	index = index.min(numIndexesMinus1);
	return index;
}
 
Example 13
Source File: BigDecimalConvertTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a negative BigDecimal to BigInteger
 */
public void testToBigIntegerNeg2() {
    String a = "-123809648392384754573567356745735.63567890295784902768787678287E+15";
    BigInteger bNumber = new BigInteger("-123809648392384754573567356745735635678902957849");
    BigDecimal aNumber = new BigDecimal(a);
    BigInteger result = aNumber.toBigInteger();
    assertTrue("incorrect value", result.equals(bNumber));
}
 
Example 14
Source File: Currency.java    From libclicker with MIT License 4 votes vote down vote up
public void multiply(double multiplier)
{
    BigDecimal tmp = new BigDecimal(mValue);
    tmp = tmp.multiply(new BigDecimal(multiplier));
    mValue = tmp.toBigInteger();
}
 
Example 15
Source File: BigIntegerTypeHandler.java    From mybaties with Apache License 2.0 4 votes vote down vote up
@Override
public BigInteger getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
  BigDecimal bigDecimal = cs.getBigDecimal(columnIndex);
  return bigDecimal == null ? null : bigDecimal.toBigInteger();
}
 
Example 16
Source File: BigIntegerTypeHandler.java    From mango with Apache License 2.0 4 votes vote down vote up
@Override
public BigInteger getNullableResult(ResultSet rs, int index) throws SQLException {
  BigDecimal bigDecimal = rs.getBigDecimal(index);
  return bigDecimal == null ? null : bigDecimal.toBigInteger();
}
 
Example 17
Source File: BigIntegerTypeHandler.java    From mybatis with Apache License 2.0 4 votes vote down vote up
@Override
public BigInteger getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
  BigDecimal bigDecimal = cs.getBigDecimal(columnIndex);
  return bigDecimal == null ? null : bigDecimal.toBigInteger();
}
 
Example 18
Source File: RequestBenefitsLookupableHelperServiceImpl.java    From kfs with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Creates <code>RequestBenefits</code> objects based on a BC expenditure line chart, object code and request amount.
 * 
 * @see org.kuali.rice.kns.lookup.KualiLookupableHelperServiceImpl#getSearchResults(java.util.Map)
 */
@Override
public List<? extends BusinessObject> getSearchResults(Map<String, String> fieldValues) {
    
  List<RequestBenefits> requestBenefits = new ArrayList<RequestBenefits>();

  // account number is used in the lookup of the labor benefit rate category code below
  String accountNumber = fieldValues.get(KFSPropertyConstants.ACCOUNT_NUMBER);
  
  // find out if we are running in rate category mode
  Boolean categoryRateCalcMode = false;
  Boolean categoryRateCalcParmExists = SpringContext.getBean(ParameterService.class).parameterExists(KfsParameterConstants.FINANCIAL_SYSTEM_ALL.class, KFSParameterKeyConstants.LdParameterConstants.ENABLE_FRINGE_BENEFIT_CALC_BY_BENEFIT_RATE_CATEGORY_IND);
  String sysParam = " ";
  if (categoryRateCalcParmExists) {
      sysParam = SpringContext.getBean(ParameterService.class).getParameterValueAsString(KfsParameterConstants.FINANCIAL_SYSTEM_ALL.class, KFSParameterKeyConstants.LdParameterConstants.ENABLE_FRINGE_BENEFIT_CALC_BY_BENEFIT_RATE_CATEGORY_IND);
      if (sysParam.equalsIgnoreCase("Y")){
          categoryRateCalcMode = true;
      }
  }
    
  Integer fiscalYear = Integer.valueOf(fieldValues.get(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR));
  String chartOfAccountsCode = fieldValues.get(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE);
  String objectCode = fieldValues.get(KFSPropertyConstants.FINANCIAL_OBJECT_CODE);
  List<LaborLedgerPositionObjectBenefit> positionObjectBenefits = laborModuleService.retrieveActiveLaborPositionObjectBenefits(fiscalYear, chartOfAccountsCode, objectCode);
  for (Iterator<LaborLedgerPositionObjectBenefit> iterator = positionObjectBenefits.iterator(); iterator.hasNext();) {
      LaborLedgerPositionObjectBenefit positionObjectBenefit = (LaborLedgerPositionObjectBenefit) iterator.next();

      KualiPercent fringePct = new KualiPercent(0);
      Boolean beneCalcExistsAndActive = true;
      LaborLedgerBenefitsCalculation benefitsCalculation = null;
      String laborBenefitRateCategoryCode = "";
      if (categoryRateCalcMode){

          // get rate category code from account
          Map<String, Object> accountLookupFields = new HashMap<String, Object>();
          accountLookupFields.put(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode);
          accountLookupFields.put(KFSPropertyConstants.ACCOUNT_NUMBER, accountNumber);
          Account account = (Account) businessObjectService.findByPrimaryKey(Account.class, accountLookupFields);
          laborBenefitRateCategoryCode = account.getLaborBenefitRateCategoryCode();

          benefitsCalculation = positionObjectBenefit.getLaborLedgerBenefitsCalculation(laborBenefitRateCategoryCode);
      } else {
          benefitsCalculation = positionObjectBenefit.getLaborLedgerBenefitsCalculation();
      }

      if (ObjectUtils.isNull(benefitsCalculation) || !benefitsCalculation.isActive()){
          beneCalcExistsAndActive = false;
          if (ObjectUtils.isNull(benefitsCalculation)){
              LOG.warn("Could not locate a benefits calculation for {" + fiscalYear + "," + chartOfAccountsCode + "," + positionObjectBenefit.getFinancialObjectBenefitsTypeCode() + "," + positionObjectBenefit.getFinancialObjectCode() + "," + laborBenefitRateCategoryCode + "}");
          }
      } else {
          fringePct = benefitsCalculation.getPositionFringeBenefitPercent();
      }

      if (beneCalcExistsAndActive){
          RequestBenefits requestBenefit = new RequestBenefits();
          requestBenefit.setFinancialObjectBenefitsTypeCode(positionObjectBenefit.getFinancialObjectBenefitsTypeCode());
          requestBenefit.setFinancialObjectBenefitsTypeDescription(positionObjectBenefit.getLaborLedgerBenefitsCalculation().getLaborLedgerBenefitsType().getPositionBenefitTypeDescription());
          requestBenefit.setPositionFringeBenefitObjectCode(positionObjectBenefit.getLaborLedgerBenefitsCalculation().getPositionFringeBenefitObjectCode());
          requestBenefit.setPositionFringeBenefitObjectCodeName(positionObjectBenefit.getLaborLedgerBenefitsCalculation().getPositionFringeBenefitObject().getFinancialObjectCodeName());
          requestBenefit.setPositionFringeBenefitPercent(positionObjectBenefit.getLaborLedgerBenefitsCalculation().getPositionFringeBenefitPercent());
          
          BigDecimal requestAmount = new BigDecimal(Integer.valueOf(fieldValues.get(KFSPropertyConstants.ACCOUNT_LINE_ANNUAL_BALANCE_AMOUNT)));
          BigDecimal fringePctDecimal = fringePct.bigDecimalValue().divide(new BigDecimal(100));
          BigDecimal result = requestAmount.multiply(fringePctDecimal).setScale(0, RoundingMode.HALF_UP);
          KualiInteger detAmount = new KualiInteger(result.toBigInteger());
          requestBenefit.setFringeDetailAmount(detAmount);
          requestBenefits.add(requestBenefit);
      }
  }

  return requestBenefits;
}
 
Example 19
Source File: BCMathFunctions.java    From jphp with Apache License 2.0 4 votes vote down vote up
public static Memory bcsqrt(Environment env, Memory operand, int scale) {
    BigDecimal value = toBigDecimal(operand);

    int compareToZero = value.compareTo(BigDecimal.ZERO);

    if (compareToZero < 0) {
        return Memory.NULL;
    } else if (compareToZero == 0) {
        return new StringMemory("0");
    }

    int compareToOne = value.compareTo(BigDecimal.ONE);

    if (compareToOne == 0)
        return new StringMemory("1");

    int cscale;

    BigDecimal initialGuess;
    if (compareToOne < 1) {
        initialGuess = BigDecimal.ONE;
        cscale = value.scale();
    } else {
        BigInteger integerPart = value.toBigInteger();

        int length = integerPart.toString().length();

        if ((length % 2) == 0)
            length--;

        length /= 2;
        initialGuess = BigDecimal.ONE.movePointRight(length);
        cscale = Math.max(scale, value.scale()) + 2;
    }

    BigDecimal guess = initialGuess;
    BigDecimal lastGuess;

    for (int iteration = 0; iteration < 50; iteration++) {
        lastGuess = guess;
        guess = value.divide(guess, cscale, RoundingMode.DOWN);
        guess = guess.add(lastGuess);
        guess = guess.divide(DECIMAL_TWO, cscale, RoundingMode.DOWN);

        if (lastGuess.equals(guess)) {
            break;
        }
    }

    value = guess;
    value = value.setScale(scale, RoundingMode.DOWN);
    return new StringMemory(value.toPlainString());
}
 
Example 20
Source File: BigIntegerType.java    From doma with Apache License 2.0 4 votes vote down vote up
@Override
protected BigInteger doGetValue(ResultSet resultSet, int index) throws SQLException {
  BigDecimal decimal = resultSet.getBigDecimal(index);
  return decimal != null ? decimal.toBigInteger() : null;
}