java.math.BigDecimal

Here are the examples of the java api class java.math.BigDecimal taken from open source projects.

1. SolarEventCalculator#getCosineSunLocalHour()

View license
private BigDecimal getCosineSunLocalHour(BigDecimal sunTrueLong, Zenith zenith) {
    BigDecimal sinSunDeclination = getSinOfSunDeclination(sunTrueLong);
    BigDecimal cosineSunDeclination = getCosineOfSunDeclination(sinSunDeclination);
    BigDecimal zenithInRads = convertDegreesToRadians(zenith.degrees());
    BigDecimal cosineZenith = BigDecimal.valueOf(Math.cos(zenithInRads.doubleValue()));
    BigDecimal sinLatitude = BigDecimal.valueOf(Math.sin(convertDegreesToRadians(location.getLatitude()).doubleValue()));
    BigDecimal cosLatitude = BigDecimal.valueOf(Math.cos(convertDegreesToRadians(location.getLatitude()).doubleValue()));
    BigDecimal sinDeclinationTimesSinLat = sinSunDeclination.multiply(sinLatitude);
    BigDecimal dividend = cosineZenith.subtract(sinDeclinationTimesSinLat);
    BigDecimal divisor = cosineSunDeclination.multiply(cosLatitude);
    return setScale(divideBy(dividend, divisor));
}

2. BigDecimalTest#test_equalsLjava_lang_Object()

Project: j2objc
Source File: BigDecimalTest.java
View license
/**
	 * @tests java.math.BigDecimal#equals(java.lang.Object)
	 */
public void test_equalsLjava_lang_Object() {
    BigDecimal equal1 = new BigDecimal(1.00D);
    BigDecimal equal2 = new BigDecimal("1.0");
    assertFalse("1.00 and 1.0 should not be equal", equal1.equals(equal2));
    equal2 = new BigDecimal(1.01D);
    assertFalse("1.00 and 1.01 should not be equal", equal1.equals(equal2));
    equal2 = new BigDecimal("1.00");
    assertFalse("1.00D and 1.00 should not be equal", equal1.equals(equal2));
    BigInteger val = new BigInteger("100");
    equal1 = new BigDecimal("1.00");
    equal2 = new BigDecimal(val, 2);
    assertTrue("1.00(string) and 1.00(bigInteger) should be equal", equal1.equals(equal2));
    equal1 = new BigDecimal(100D);
    equal2 = new BigDecimal("2.34576");
    assertFalse("100D and 2.34576 should not be equal", equal1.equals(equal2));
    assertFalse("bigDecimal 100D does not equal string 23415", equal1.equals("23415"));
}

3. ChargeData#toShareAccountChargeData()

Project: incubator-fineract
Source File: ChargeData.java
View license
public ShareAccountChargeData toShareAccountChargeData() {
    final Long shareChargeId = null;
    final Long shareAccountId = null;
    final BigDecimal amountPaid = BigDecimal.ZERO;
    final BigDecimal amountWaived = BigDecimal.ZERO;
    final BigDecimal amountWrittenOff = BigDecimal.ZERO;
    final BigDecimal amountOutstanding = BigDecimal.ZERO;
    final BigDecimal percentage = BigDecimal.ZERO;
    final BigDecimal amountPercentageAppliedTo = BigDecimal.ZERO;
    final Collection<ChargeData> chargeOptions = null;
    final Boolean isActive = null;
    final BigDecimal chargeAmountOrPercentage = BigDecimal.ZERO;
    return new ShareAccountChargeData(shareChargeId, this.id, shareAccountId, this.name, this.currency, this.amount, amountPaid, amountWaived, amountWrittenOff, amountOutstanding, this.chargeTimeType, this.chargeCalculationType, percentage, amountPercentageAppliedTo, chargeOptions, isActive, chargeAmountOrPercentage);
}

4. LoanTransactionData#LoanTransactionDataForDisbursalTemplate()

View license
public static LoanTransactionData LoanTransactionDataForDisbursalTemplate(final LoanTransactionEnumData transactionType, final LocalDate expectedDisbursedOnLocalDateForTemplate, final BigDecimal disburseAmountForTemplate, final Collection<PaymentTypeData> paymentOptions, final BigDecimal retriveLastEmiAmount, final LocalDate possibleNextRepaymentDate) {
    final Long id = null;
    final Long officeId = null;
    final String officeName = null;
    final PaymentDetailData paymentDetailData = null;
    final CurrencyData currency = null;
    final BigDecimal unrecognizedIncomePortion = null;
    final BigDecimal principalPortion = null;
    ;
    final BigDecimal interestPortion = null;
    final BigDecimal feeChargesPortion = null;
    final BigDecimal penaltyChargesPortion = null;
    final BigDecimal overpaymentPortion = null;
    final String externalId = null;
    final BigDecimal outstandingLoanBalance = null;
    final AccountTransferData transfer = null;
    final LocalDate submittedOnDate = null;
    final boolean manuallyReversed = false;
    return new LoanTransactionData(id, officeId, officeName, transactionType, paymentDetailData, currency, expectedDisbursedOnLocalDateForTemplate, disburseAmountForTemplate, principalPortion, interestPortion, feeChargesPortion, penaltyChargesPortion, overpaymentPortion, unrecognizedIncomePortion, paymentOptions, transfer, externalId, retriveLastEmiAmount, outstandingLoanBalance, submittedOnDate, manuallyReversed, possibleNextRepaymentDate);
}

5. BigDecimalTest#test_hashCode()

Project: j2objc
Source File: BigDecimalTest.java
View license
/**
	 * @tests java.math.BigDecimal#hashCode()
	 */
public void test_hashCode() {
    // anything that is equal must have the same hashCode
    BigDecimal hash = new BigDecimal("1.00");
    BigDecimal hash2 = new BigDecimal(1.00D);
    assertTrue("the hashCode of 1.00 and 1.00D is equal", hash.hashCode() != hash2.hashCode() && !hash.equals(hash2));
    hash2 = new BigDecimal("1.0");
    assertTrue("the hashCode of 1.0 and 1.00 is equal", hash.hashCode() != hash2.hashCode() && !hash.equals(hash2));
    BigInteger val = new BigInteger("100");
    hash2 = new BigDecimal(val, 2);
    assertTrue("hashCode of 1.00 and 1.00(bigInteger) is not equal", hash.hashCode() == hash2.hashCode() && hash.equals(hash2));
    hash = new BigDecimal(value, 2);
    hash2 = new BigDecimal("-1233456.0000");
    assertTrue("hashCode of 123459.08 and -1233456.0000 is not equal", hash.hashCode() != hash2.hashCode() && !hash.equals(hash2));
    hash2 = new BigDecimal(value.negate(), 2);
    assertTrue("hashCode of 123459.08 and -123459.08 is not equal", hash.hashCode() != hash2.hashCode() && !hash.equals(hash2));
}

6. SolarEventCalculator#computeSolarEventTime()

View license
private BigDecimal computeSolarEventTime(Zenith solarZenith, Calendar date, boolean isSunrise) {
    date.setTimeZone(this.timeZone);
    BigDecimal longitudeHour = getLongitudeHour(date, isSunrise);
    BigDecimal meanAnomaly = getMeanAnomaly(longitudeHour);
    BigDecimal sunTrueLong = getSunTrueLongitude(meanAnomaly);
    BigDecimal cosineSunLocalHour = getCosineSunLocalHour(sunTrueLong, solarZenith);
    if ((cosineSunLocalHour.doubleValue() < -1.0) || (cosineSunLocalHour.doubleValue() > 1.0)) {
        return null;
    }
    BigDecimal sunLocalHour = getSunLocalHour(cosineSunLocalHour, isSunrise);
    BigDecimal localMeanTime = getLocalMeanTime(sunTrueLong, longitudeHour, sunLocalHour);
    BigDecimal localTime = getLocalTime(localMeanTime, date);
    return localTime;
}

7. SolarEventCalculator#getRightAscension()

View license
/**
     * Computes the suns right ascension, RA in the algorithm, adjusting for the quadrant of L and turning it
     * into degree-hours. Will be in the range [0,360].
     *
     * @param sunTrueLong
     *            Suns true longitude, in <code>BigDecimal</code>
     * @return suns right ascension in degree-hours, in <code>BigDecimal</code> form.
     */
private BigDecimal getRightAscension(BigDecimal sunTrueLong) {
    BigDecimal tanL = new BigDecimal(Math.tan(convertDegreesToRadians(sunTrueLong).doubleValue()));
    BigDecimal innerParens = multiplyBy(convertRadiansToDegrees(tanL), new BigDecimal("0.91764"));
    BigDecimal rightAscension = new BigDecimal(Math.atan(convertDegreesToRadians(innerParens).doubleValue()));
    rightAscension = setScale(convertRadiansToDegrees(rightAscension));
    if (rightAscension.doubleValue() < 0) {
        rightAscension = rightAscension.add(BigDecimal.valueOf(360));
    } else if (rightAscension.doubleValue() > 360) {
        rightAscension = rightAscension.subtract(BigDecimal.valueOf(360));
    }
    BigDecimal ninety = BigDecimal.valueOf(90);
    BigDecimal longitudeQuadrant = sunTrueLong.divide(ninety, 0, RoundingMode.FLOOR);
    longitudeQuadrant = longitudeQuadrant.multiply(ninety);
    BigDecimal rightAscensionQuadrant = rightAscension.divide(ninety, 0, RoundingMode.FLOOR);
    rightAscensionQuadrant = rightAscensionQuadrant.multiply(ninety);
    BigDecimal augend = longitudeQuadrant.subtract(rightAscensionQuadrant);
    return divideBy(rightAscension.add(augend), BigDecimal.valueOf(15));
}

8. BitMarketAdapters#adaptTicker()

Project: XChange
Source File: BitMarketAdapters.java
View license
/**
   * Adapts BitMarket ticker to Ticker.
   *
   * @param bitMarketTicker
   * @param currencyPair
   * @return
   */
public static Ticker adaptTicker(BitMarketTicker bitMarketTicker, CurrencyPair currencyPair) {
    BigDecimal bid = bitMarketTicker.getBid();
    BigDecimal ask = bitMarketTicker.getAsk();
    BigDecimal high = bitMarketTicker.getHigh();
    BigDecimal low = bitMarketTicker.getLow();
    BigDecimal volume = bitMarketTicker.getVolume();
    BigDecimal vwap = bitMarketTicker.getVwap();
    BigDecimal last = bitMarketTicker.getLast();
    return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).volume(volume).vwap(vwap).build();
}

9. BitstampAdapters#adaptTicker()

Project: XChange
Source File: BitstampAdapters.java
View license
/**
   * Adapts a BitstampTicker to a Ticker Object
   *
   * @param bitstampTicker The exchange specific ticker
   * @param currencyPair (e.g. BTC/USD)
   * @return The ticker
   */
public static Ticker adaptTicker(BitstampTicker bitstampTicker, CurrencyPair currencyPair) {
    BigDecimal last = bitstampTicker.getLast();
    BigDecimal bid = bitstampTicker.getBid();
    BigDecimal ask = bitstampTicker.getAsk();
    BigDecimal high = bitstampTicker.getHigh();
    BigDecimal low = bitstampTicker.getLow();
    BigDecimal vwap = bitstampTicker.getVwap();
    BigDecimal volume = bitstampTicker.getVolume();
    Date timestamp = new Date(bitstampTicker.getTimestamp() * 1000L);
    return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).vwap(vwap).volume(volume).timestamp(timestamp).build();
}

10. BTCChinaAdapters#adaptTicker()

Project: XChange
Source File: BTCChinaAdapters.java
View license
public static Ticker adaptTicker(BTCChinaTickerObject ticker, CurrencyPair currencyPair) {
    BigDecimal last = ticker.getLast();
    BigDecimal high = ticker.getHigh();
    BigDecimal low = ticker.getLow();
    BigDecimal vwap = ticker.getVwap();
    BigDecimal buy = ticker.getBuy();
    BigDecimal sell = ticker.getSell();
    BigDecimal volume = ticker.getVol();
    Date date = adaptDate(ticker.getDate());
    return new Ticker.Builder().currencyPair(currencyPair).last(last).high(high).low(low).vwap(vwap).bid(buy).ask(sell).volume(volume).timestamp(date).build();
}

11. BTCEAdapters#adaptTicker()

Project: XChange
Source File: BTCEAdapters.java
View license
/**
   * Adapts a BTCETicker to a Ticker Object
   *
   * @param bTCETicker
   * @return
   */
public static Ticker adaptTicker(BTCETicker bTCETicker, CurrencyPair currencyPair) {
    BigDecimal last = bTCETicker.getLast();
    BigDecimal bid = bTCETicker.getSell();
    BigDecimal ask = bTCETicker.getBuy();
    BigDecimal high = bTCETicker.getHigh();
    BigDecimal low = bTCETicker.getLow();
    BigDecimal avg = bTCETicker.getAvg();
    BigDecimal volume = bTCETicker.getVolCur();
    Date timestamp = DateUtils.fromMillisUtc(bTCETicker.getUpdated() * 1000L);
    return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).vwap(avg).volume(volume).timestamp(timestamp).build();
}

12. EmpoExAdapters#adaptEmpoExTicker()

Project: XChange
Source File: EmpoExAdapters.java
View license
public static Ticker adaptEmpoExTicker(EmpoExTicker raw) {
    CurrencyPair currencyPair = EmpoExUtils.toCurrencyPair(raw.getPairname());
    BigDecimal last = new BigDecimal(raw.getLast().replace(",", ""));
    BigDecimal high = new BigDecimal(raw.getHigh().replace(",", ""));
    BigDecimal low = new BigDecimal(raw.getLow().replace(",", ""));
    BigDecimal bid = new BigDecimal(raw.getBid().replace(",", ""));
    BigDecimal ask = new BigDecimal(raw.getAsk().replace(",", ""));
    BigDecimal counterVolume = new BigDecimal(raw.getBaseVolume24hr().replace(",", ""));
    BigDecimal volume = counterVolume.divide(last, new MathContext(8, RoundingMode.HALF_UP));
    return new Ticker.Builder().currencyPair(currencyPair).last(last).high(high).low(low).bid(bid).ask(ask).volume(volume).build();
}

13. ChargeData#toSavingsAccountChargeData()

Project: incubator-fineract
Source File: ChargeData.java
View license
public SavingsAccountChargeData toSavingsAccountChargeData() {
    final Long savingsChargeId = null;
    final Long savingsAccountId = null;
    final BigDecimal amountPaid = BigDecimal.ZERO;
    final BigDecimal amountWaived = BigDecimal.ZERO;
    final BigDecimal amountWrittenOff = BigDecimal.ZERO;
    final BigDecimal amountOutstanding = BigDecimal.ZERO;
    final BigDecimal percentage = BigDecimal.ZERO;
    final BigDecimal amountPercentageAppliedTo = BigDecimal.ZERO;
    final Collection<ChargeData> chargeOptions = null;
    final LocalDate dueAsOfDate = null;
    final Boolean isActive = null;
    final LocalDate inactivationDate = null;
    return SavingsAccountChargeData.instance(savingsChargeId, this.id, savingsAccountId, this.name, this.currency, this.amount, amountPaid, amountWaived, amountWrittenOff, amountOutstanding, this.chargeTimeType, dueAsOfDate, this.chargeCalculationType, percentage, amountPercentageAppliedTo, chargeOptions, this.penalty, this.feeOnMonthDay, this.feeInterval, isActive, inactivationDate);
}

14. BigDecimalTest#test_floatValue()

Project: j2objc
Source File: BigDecimalTest.java
View license
/**
	 * @tests java.math.BigDecimal#floatValue()
	 */
public void test_floatValue() {
    BigDecimal fl1 = new BigDecimal("234563782344567");
    assertTrue("the float representation of bigDecimal 234563782344567", fl1.floatValue() == 234563782344567f);
    BigDecimal fl2 = new BigDecimal(2.345E37);
    assertTrue("the float representation of bigDecimal 2.345E37", fl2.floatValue() == 2.345E37F);
    fl2 = new BigDecimal(-1.00E-44);
    assertTrue("the float representation of bigDecimal -1.00E-44", fl2.floatValue() == -1.00E-44F);
    fl2 = new BigDecimal(-3E12);
    assertTrue("the float representation of bigDecimal -3E12", fl2.floatValue() == -3E12F);
    fl2 = new BigDecimal(Double.MAX_VALUE);
    assertTrue("A number can't be represented by float should return infinity", fl2.floatValue() == Float.POSITIVE_INFINITY);
    fl2 = new BigDecimal(-Double.MAX_VALUE);
    assertTrue("A number can't be represented by float should return infinity", fl2.floatValue() == Float.NEGATIVE_INFINITY);
}

15. BigDecimalTest#test_maxLjava_math_BigDecimal()

Project: j2objc
Source File: BigDecimalTest.java
View license
/**
	 * @tests java.math.BigDecimal#max(java.math.BigDecimal)
	 */
public void test_maxLjava_math_BigDecimal() {
    BigDecimal max1 = new BigDecimal(value2, 1);
    BigDecimal max2 = new BigDecimal(value2, 4);
    assertTrue("1233456000.0 is not greater than 1233456", max1.max(max2).equals(max1));
    max1 = new BigDecimal(-1.224D);
    max2 = new BigDecimal(-1.2245D);
    assertTrue("-1.224 is not greater than -1.2245", max1.max(max2).equals(max1));
    max1 = new BigDecimal(123E18);
    max2 = new BigDecimal(123E19);
    assertTrue("123E19 is the not the max", max1.max(max2).equals(max2));
}

16. BigDecimalTest#test_movePointLeftI()

Project: j2objc
Source File: BigDecimalTest.java
View license
/**
	 * @tests java.math.BigDecimal#movePointLeft(int)
	 */
public void test_movePointLeftI() {
    BigDecimal movePtLeft = new BigDecimal("123456265.34");
    BigDecimal alreadyMoved = movePtLeft.movePointLeft(5);
    assertTrue("move point left 5 failed", alreadyMoved.scale() == 7 && alreadyMoved.toString().equals("1234.5626534"));
    movePtLeft = new BigDecimal(value2.negate(), 0);
    alreadyMoved = movePtLeft.movePointLeft(12);
    assertTrue("move point left 12 failed", alreadyMoved.scale() == 12 && alreadyMoved.toString().equals("-0.012334560000"));
    movePtLeft = new BigDecimal(123E18);
    alreadyMoved = movePtLeft.movePointLeft(2);
    assertTrue("move point left 2 failed", alreadyMoved.scale() == movePtLeft.scale() + 2 && alreadyMoved.doubleValue() == 1.23E18);
    movePtLeft = new BigDecimal(1.123E-12);
    alreadyMoved = movePtLeft.movePointLeft(3);
    assertTrue("move point left 3 failed", alreadyMoved.scale() == movePtLeft.scale() + 3 && alreadyMoved.doubleValue() == 1.123E-15);
    movePtLeft = new BigDecimal(value, 2);
    alreadyMoved = movePtLeft.movePointLeft(-2);
    assertTrue("move point left -2 failed", alreadyMoved.scale() == movePtLeft.scale() - 2 && alreadyMoved.toString().equals("12345908"));
}

17. TestDefaultInvoiceUserApi#testOriginalAmountCharged()

View license
@Test(groups = "slow")
public void testOriginalAmountCharged() throws Exception {
    final Invoice initialInvoice = invoiceUserApi.getInvoice(invoiceId, callContext);
    final BigDecimal originalAmountCharged = initialInvoice.getOriginalChargedAmount();
    final BigDecimal amountCharged = initialInvoice.getChargedAmount();
    Assert.assertEquals(originalAmountCharged.compareTo(amountCharged), 0);
    ((ClockMock) clock).addDays(1);
    // Sleep at least one sec to make sure created_date for the external charge is different than the created date for the invoice itself
    CallContext newCallContextLater = new DefaultCallContext(callContext.getTenantId(), callContext.getUserName(), callContext.getCallOrigin(), callContext.getUserType(), callContext.getUserToken(), clock);
    // Post an external charge
    final BigDecimal externalChargeAmount = BigDecimal.TEN;
    final InvoiceItem externalCharge = new ExternalChargeInvoiceItem(invoiceId, accountId, null, UUID.randomUUID().toString(), clock.getUTCToday(), externalChargeAmount, accountCurrency);
    final InvoiceItem externalChargeInvoiceItem = invoiceUserApi.insertExternalCharges(accountId, clock.getUTCToday(), ImmutableList.<InvoiceItem>of(externalCharge), newCallContextLater).get(0);
    final Invoice newInvoice = invoiceUserApi.getInvoice(invoiceId, callContext);
    final BigDecimal newOriginalAmountCharged = newInvoice.getOriginalChargedAmount();
    final BigDecimal newAmountCharged = newInvoice.getChargedAmount();
    final BigDecimal expectedChargedAmount = newInvoice.getOriginalChargedAmount().add(externalChargeInvoiceItem.getAmount());
    Assert.assertEquals(originalAmountCharged.compareTo(newOriginalAmountCharged), 0);
    Assert.assertEquals(newAmountCharged.compareTo(expectedChargedAmount), 0);
}

18. ValueMetaTest#testCompareBigNumberNormalStorageData()

Project: pentaho-kettle
Source File: ValueMetaTest.java
View license
public void testCompareBigNumberNormalStorageData() throws Exception {
    BigDecimal number1 = new BigDecimal("987908798769876.23943409");
    BigDecimal number2 = new BigDecimal("999908798769876.23943409");
    BigDecimal number3 = new BigDecimal("955908798769876.23943409");
    BigDecimal number4 = new BigDecimal("987908798769876.23943409");
    BigDecimal number5 = null;
    BigDecimal number6 = null;
    ValueMetaInterface one = new ValueMeta("one", ValueMetaInterface.TYPE_BIGNUMBER);
    ValueMetaInterface two = new ValueMeta("two", ValueMetaInterface.TYPE_BIGNUMBER);
    assertTrue(one.compare(number1, number2) < 0);
    assertTrue(one.compare(number1, number3) > 0);
    assertTrue(one.compare(number1, number4) == 0);
    assertTrue(one.compare(number1, number5) != 0);
    assertTrue(one.compare(number5, number6) == 0);
    assertTrue(one.compare(number1, two, number2) < 0);
    assertTrue(one.compare(number1, two, number3) > 0);
    assertTrue(one.compare(number1, two, number4) == 0);
    assertTrue(one.compare(number1, two, number5) != 0);
    assertTrue(one.compare(number5, two, number6) == 0);
}

19. VariationTestingClientStrategyTest#rangeTest()

View license
@Test
public void rangeTest() {
    BigDecimal ratioTotal = new BigDecimal(1.0);
    BigDecimal currentMax = new BigDecimal(0.0);
    BigDecimal r1 = new BigDecimal(0.9);
    BigDecimal r2 = new BigDecimal(0.1);
    NumberRange range1 = new NumberRange(currentMax, currentMax.add(r1.divide(ratioTotal, 5, BigDecimal.ROUND_UP)));
    currentMax = currentMax.add(r1);
    NumberRange range2 = new NumberRange(currentMax.add(new BigDecimal(0.0001)), currentMax.add(r2.divide(ratioTotal, 5, BigDecimal.ROUND_UP)));
    BigDecimal t = new BigDecimal(0.900001);
    Assert.assertTrue(range1.containsNumber(t));
    Assert.assertFalse(range2.containsNumber(t));
    BigDecimal t2 = new BigDecimal(0.901);
    Assert.assertFalse(range1.containsNumber(t2));
    Assert.assertTrue(range2.containsNumber(t2));
}

20. ANXAdapters#adaptTicker()

Project: XChange
Source File: ANXAdapters.java
View license
public static Ticker adaptTicker(ANXTicker anxTicker) {
    BigDecimal volume = anxTicker.getVol().getValue();
    BigDecimal last = anxTicker.getLast().getValue();
    BigDecimal bid = anxTicker.getBuy().getValue();
    BigDecimal ask = anxTicker.getSell().getValue();
    BigDecimal high = anxTicker.getHigh().getValue();
    BigDecimal low = anxTicker.getLow().getValue();
    Date timestamp = new Date(anxTicker.getNow() / 1000);
    CurrencyPair currencyPair = adaptCurrencyPair(anxTicker.getVol().getCurrency(), anxTicker.getAvg().getCurrency());
    return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).volume(volume).timestamp(timestamp).build();
}

21. BitfinexAdapters#adaptTicker()

Project: XChange
Source File: BitfinexAdapters.java
View license
public static Ticker adaptTicker(BitfinexTicker bitfinexTicker, CurrencyPair currencyPair) {
    BigDecimal last = bitfinexTicker.getLast_price();
    BigDecimal bid = bitfinexTicker.getBid();
    BigDecimal ask = bitfinexTicker.getAsk();
    BigDecimal high = bitfinexTicker.getHigh();
    BigDecimal low = bitfinexTicker.getLow();
    BigDecimal volume = bitfinexTicker.getVolume();
    Date timestamp = DateUtils.fromMillisUtc((long) (bitfinexTicker.getTimestamp() * 1000L));
    return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).volume(volume).timestamp(timestamp).build();
}

22. BitKonanAdapters#adaptTicker()

Project: XChange
Source File: BitKonanAdapters.java
View license
/**
   * Adapts a HitbtcTicker to a Ticker Object
   *
   * @param bitKonanTicker The exchange specific ticker
   * @param currencyPair (e.g. BTC/USD)
   * @return The ticker
   */
public static Ticker adaptTicker(BitKonanTicker bitKonanTicker, CurrencyPair currencyPair) {
    BigDecimal bid = bitKonanTicker.getBid();
    BigDecimal ask = bitKonanTicker.getAsk();
    BigDecimal high = bitKonanTicker.getHigh();
    BigDecimal low = bitKonanTicker.getLow();
    BigDecimal last = bitKonanTicker.getLast();
    BigDecimal volume = bitKonanTicker.getVolume();
    return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).volume(volume).build();
}

23. BittrexAdapters#adaptTicker()

Project: XChange
Source File: BittrexAdapters.java
View license
public static Ticker adaptTicker(BittrexTicker bittrexTicker, CurrencyPair currencyPair) {
    BigDecimal last = bittrexTicker.getLast();
    BigDecimal bid = bittrexTicker.getBid();
    BigDecimal ask = bittrexTicker.getAsk();
    BigDecimal high = bittrexTicker.getHigh();
    BigDecimal low = bittrexTicker.getLow();
    BigDecimal volume = bittrexTicker.getVolume();
    Date timestamp = BittrexUtils.toDate(bittrexTicker.getTimeStamp());
    return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).volume(volume).timestamp(timestamp).build();
}

24. BTCCentralAdapters#adaptTicker()

Project: XChange
Source File: BTCCentralAdapters.java
View license
/**
   * Adapts a BTCCentralTicker to a Ticker Object
   *
   * @param btcCentralTicker The exchange specific ticker
   * @param currencyPair (e.g. BTC/USD)
   * @return The ticker
   */
public static Ticker adaptTicker(BTCCentralTicker btcCentralTicker, CurrencyPair currencyPair) {
    BigDecimal bid = btcCentralTicker.getBid();
    BigDecimal ask = btcCentralTicker.getAsk();
    BigDecimal high = btcCentralTicker.getHigh();
    BigDecimal low = btcCentralTicker.getLow();
    BigDecimal last = btcCentralTicker.getPrice();
    BigDecimal volume = btcCentralTicker.getVolume();
    Date timestamp = new Date(btcCentralTicker.getAt() * 1000L);
    return new Ticker.Builder().currencyPair(currencyPair).bid(bid).ask(ask).high(high).low(low).last(last).volume(volume).timestamp(timestamp).build();
}

25. CexIOAdapters#adaptTicker()

Project: XChange
Source File: CexIOAdapters.java
View license
/**
   * Adapts a CexIOTicker to a Ticker Object
   *
   * @param ticker The exchange specific ticker
   * @param currencyPair The currency pair (e.g. BTC/USD)
   * @return The ticker
   */
public static Ticker adaptTicker(CexIOTicker ticker, CurrencyPair currencyPair) {
    BigDecimal last = ticker.getLast();
    BigDecimal bid = ticker.getBid();
    BigDecimal ask = ticker.getAsk();
    BigDecimal high = ticker.getHigh();
    BigDecimal low = ticker.getLow();
    BigDecimal volume = ticker.getVolume();
    Date timestamp = new Date(ticker.getTimestamp() * 1000L);
    return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).volume(volume).timestamp(timestamp).build();
}

26. CleverCoinAdapters#adaptTicker()

Project: XChange
Source File: CleverCoinAdapters.java
View license
/**
   * Adapts a CleverCoinTicker to a Ticker Object
   *
   * @param cleverCoinTicker The exchange specific ticker
   * @param currencyPair (e.g. BTC/USD)
   * @return The ticker
   */
public static Ticker adaptTicker(CleverCoinTicker cleverCoinTicker, CurrencyPair currencyPair) {
    BigDecimal last = cleverCoinTicker.getLast();
    BigDecimal bid = cleverCoinTicker.getBid();
    BigDecimal ask = cleverCoinTicker.getAsk();
    BigDecimal high = cleverCoinTicker.getHigh();
    BigDecimal low = cleverCoinTicker.getLow();
    BigDecimal volume = cleverCoinTicker.getVolume();
    Date timestamp = new Date(cleverCoinTicker.getTimestamp() * 1000L);
    return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).volume(volume).timestamp(timestamp).build();
}

27. CoinbaseExAdapters#adaptTicker()

Project: XChange
Source File: CoinbaseExAdapters.java
View license
public static Ticker adaptTicker(CoinbaseExProductTicker ticker, CoinbaseExProductStats stats, CoinbaseExProductBook book, CurrencyPair currencyPair) {
    BigDecimal last = ticker != null ? ticker.getPrice() : null;
    BigDecimal high = stats != null ? stats.getHigh() : null;
    BigDecimal low = stats != null ? stats.getLow() : null;
    BigDecimal buy = book != null ? book.getBestBid().getPrice() : null;
    BigDecimal sell = book != null ? book.getBestAsk().getPrice() : null;
    BigDecimal volume = stats != null ? stats.getVolume() : null;
    Date date = ticker != null ? ticker.getTime() : new Date();
    return new Ticker.Builder().currencyPair(currencyPair).last(last).high(high).low(low).bid(buy).ask(sell).volume(volume).timestamp(date).build();
}

28. CoinmateAdapters#adaptTicker()

Project: XChange
Source File: CoinmateAdapters.java
View license
/**
   * Adapts a CoinmateTicker to a Ticker Object
   *
   * @param coinmateTicker The exchange specific ticker
   * @param currencyPair (e.g. BTC/USD)
   * @return The ticker
   */
public static Ticker adaptTicker(CoinmateTicker coinmateTicker, CurrencyPair currencyPair) {
    BigDecimal last = coinmateTicker.getData().getLast();
    BigDecimal bid = coinmateTicker.getData().getBid();
    BigDecimal ask = coinmateTicker.getData().getAsk();
    BigDecimal high = coinmateTicker.getData().getHigh();
    BigDecimal low = coinmateTicker.getData().getLow();
    BigDecimal volume = coinmateTicker.getData().getAmount();
    return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).volume(volume).build();
}

29. CryptonitAdapters#adaptTicker()

Project: XChange
Source File: CryptonitAdapters.java
View license
/**
   * Adapts a cryptonitTicker to a Ticker Object
   * 
   * @param cryptonitTicker
   * @return
   */
public static Ticker adaptTicker(CryptonitTicker cryptonitTicker, CurrencyPair currencyPair) {
    CryptonitRate rate = cryptonitTicker.getRate();
    BigDecimal last = rate.getLast();
    BigDecimal high = rate.getHigh();
    BigDecimal low = rate.getLow();
    BigDecimal bid = rate.getBid();
    BigDecimal ask = rate.getAsk();
    BigDecimal volume = cryptonitTicker.getVolume().getVolume(currencyPair.base.getCurrencyCode());
    return new Ticker.Builder().currencyPair(currencyPair).last(last).high(high).low(low).bid(bid).ask(ask).volume(volume).build();
}

30. CryptsyAdapters#adaptTicker()

Project: XChange
Source File: CryptsyAdapters.java
View license
/**
   * Adapts CryptsyGetMarketsReturn DTO to XChange standard Ticker DTO Note: Cryptsy does not natively have a Ticker method, so getMarkets function
   * will have to be called to get summary data
   *
   * @param marketsReturnData Raw returned data from Cryptsy, CryptsyGetMarketsReturn DTO
   * @param currencyPair The market for which this CryptsyGetMarketsReturn belongs to (Usually not given in Cryptsy response)
   * @return Standard XChange Ticker DTO
   */
public static Ticker adaptTicker(CryptsyGetMarketsReturn marketsReturnData, CurrencyPair currencyPair) {
    List<CryptsyMarketData> marketData = marketsReturnData.getReturnValue();
    String label = currencyPair.toString().replace("_", "/");
    CryptsyMarketData targetMarket = null;
    for (CryptsyMarketData currMarket : marketData) {
        if (currMarket.getLabel().equalsIgnoreCase(label)) {
            targetMarket = currMarket;
            break;
        }
    }
    BigDecimal last = targetMarket.getLast();
    BigDecimal bid = null;
    BigDecimal ask = null;
    BigDecimal high = targetMarket.getHigh();
    BigDecimal low = targetMarket.getLow();
    BigDecimal volume = targetMarket.get24hVolume();
    Date timestamp = targetMarket.getCreatedTime();
    return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).volume(volume).timestamp(timestamp).build();
}

31. CryptsyAdapters#adaptPublicTicker()

Project: XChange
Source File: CryptsyAdapters.java
View license
/**
   * Adapts CryptsyPublicMarketData DTO to XChange standard Ticker DTO Note: Cryptsy does not natively have a Ticker method, so getCryptsyMarketData
   * function will have to be called to get summary data
   *
   * @param publicMarketData Raw returned data from Cryptsy, CryptsyGetMarketsReturn DTO
   * @return Standard XChange Ticker DTO
   */
public static Ticker adaptPublicTicker(CryptsyPublicMarketData publicMarketData) {
    List<CryptsyPublicTrade> recentTrades = publicMarketData.getRecentTrades();
    BigDecimal last = (recentTrades != null && recentTrades.size() > 0) ? recentTrades.get(0).getPrice() : null;
    List<CryptsyPublicOrder> bids = publicMarketData.getBuyOrders();
    BigDecimal bid = (bids != null && bids.size() > 0) ? bids.get(0).getPrice() : null;
    List<CryptsyPublicOrder> asks = publicMarketData.getSellOrders();
    BigDecimal ask = (asks != null && asks.size() > 0) ? asks.get(0).getPrice() : null;
    BigDecimal high = null;
    BigDecimal low = null;
    BigDecimal volume = publicMarketData.getVolume();
    Date timestamp = publicMarketData.getLastTradeTime();
    return new Ticker.Builder().currencyPair(adaptCurrencyPair(publicMarketData)).last(last).bid(bid).ask(ask).high(high).low(low).volume(volume).timestamp(timestamp).build();
}

32. HitbtcAdapters#adaptTicker()

Project: XChange
Source File: HitbtcAdapters.java
View license
/**
   * Adapts a HitbtcTicker to a Ticker Object
   *
   * @param hitbtcTicker The exchange specific ticker
   * @param currencyPair (e.g. BTC/USD)
   * @return The ticker
   */
public static Ticker adaptTicker(HitbtcTicker hitbtcTicker, CurrencyPair currencyPair) {
    BigDecimal bid = hitbtcTicker.getBid();
    BigDecimal ask = hitbtcTicker.getAsk();
    BigDecimal high = hitbtcTicker.getHigh();
    BigDecimal low = hitbtcTicker.getLow();
    BigDecimal last = hitbtcTicker.getLast();
    BigDecimal volume = hitbtcTicker.getVolume();
    Date timestamp = new Date(hitbtcTicker.getTimestamp());
    return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).volume(volume).timestamp(timestamp).build();
}

33. ItBitAdapters#adaptTicker()

Project: XChange
Source File: ItBitAdapters.java
View license
public static Ticker adaptTicker(CurrencyPair currencyPair, ItBitTicker itBitTicker) {
    BigDecimal bid = itBitTicker.getBid();
    BigDecimal ask = itBitTicker.getAsk();
    BigDecimal high = itBitTicker.getHighToday();
    BigDecimal low = itBitTicker.getLowToday();
    BigDecimal last = itBitTicker.getLastPrice();
    BigDecimal volume = itBitTicker.getVolume24h();
    Date timestamp = itBitTicker.getTimestamp() != null ? parseDate(itBitTicker.getTimestamp()) : null;
    return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).volume(volume).timestamp(timestamp).build();
}

34. MercadoBitcoinAdapters#adaptTicker()

Project: XChange
Source File: MercadoBitcoinAdapters.java
View license
/**
   * Adapts a MercadoBitcoinTicker to a Ticker Object
   *
   * @param mercadoBitcoinTicker The exchange specific ticker
   * @param currencyPair (e.g. BTC/USD)
   * @return The ticker
   */
public static Ticker adaptTicker(MercadoBitcoinTicker mercadoBitcoinTicker, CurrencyPair currencyPair) {
    BigDecimal last = mercadoBitcoinTicker.getTicker().getLast();
    BigDecimal bid = mercadoBitcoinTicker.getTicker().getBuy();
    BigDecimal ask = mercadoBitcoinTicker.getTicker().getSell();
    BigDecimal high = mercadoBitcoinTicker.getTicker().getHigh();
    BigDecimal low = mercadoBitcoinTicker.getTicker().getLow();
    BigDecimal volume = mercadoBitcoinTicker.getTicker().getVol();
    Date timestamp = new Date(mercadoBitcoinTicker.getTicker().getDate() * 1000L);
    return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).volume(volume).timestamp(timestamp).build();
}

35. PoloniexAdapters#adaptPoloniexTicker()

Project: XChange
Source File: PoloniexAdapters.java
View license
public static Ticker adaptPoloniexTicker(PoloniexTicker poloniexTicker, CurrencyPair currencyPair) {
    PoloniexMarketData marketData = poloniexTicker.getPoloniexMarketData();
    BigDecimal last = marketData.getLast();
    BigDecimal bid = marketData.getHighestBid();
    BigDecimal ask = marketData.getLowestAsk();
    BigDecimal high = marketData.getHigh24hr();
    BigDecimal low = marketData.getLow24hr();
    BigDecimal volume = marketData.getQuoteVolume();
    return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).volume(volume).build();
}

36. YacunaAdapters#adaptTicker()

Project: XChange
Source File: YacunaAdapters.java
View license
public static Ticker adaptTicker(YacunaTicker ticker, CurrencyPair currencyPair) {
    BigDecimal last = ticker.getOverallStatistics() != null && ticker.getOverallStatistics().getLastPricePair() != null ? ticker.getOverallStatistics().getLastPricePair().getAmount() : null;
    BigDecimal high = ticker.getDailyStatistics() != null && ticker.getDailyStatistics().getHighPricePair() != null ? ticker.getDailyStatistics().getHighPricePair().getAmount() : null;
    BigDecimal low = ticker.getDailyStatistics() != null && ticker.getDailyStatistics().getLowPricePair() != null ? ticker.getDailyStatistics().getLowPricePair().getAmount() : null;
    BigDecimal buy = ticker.getOverallStatistics() != null && ticker.getOverallStatistics().getBuyPricePair() != null ? ticker.getOverallStatistics().getBuyPricePair().getAmount() : null;
    BigDecimal sell = ticker.getOverallStatistics() != null && ticker.getOverallStatistics().getSellPricePair() != null ? ticker.getOverallStatistics().getSellPricePair().getAmount() : null;
    BigDecimal volume = ticker.getDailyStatistics() != null && ticker.getDailyStatistics().getVolumePair() != null ? ticker.getDailyStatistics().getVolumePair().getAmount() : null;
    Date date = ticker.getOverallStatistics() != null ? ticker.getOverallStatistics().getTimestamp() : new Date();
    return new Ticker.Builder().currencyPair(currencyPair).last(last).high(high).low(low).bid(buy).ask(sell).volume(volume).timestamp(date).build();
}

37. ClientChargeData#template()

View license
public static ClientChargeData template(final Collection<ChargeData> chargeOptions) {
    final Long id = null;
    final Long clientId = null;
    final Long chargeId = null;
    final String name = null;
    final EnumOptionData chargeTimeType = null;
    final LocalDate dueDate = null;
    final EnumOptionData chargeCalculationType = null;
    final CurrencyData currency = null;
    final BigDecimal amount = null;
    final BigDecimal amountPaid = null;
    final BigDecimal amountWaived = null;
    final BigDecimal amountWrittenOff = null;
    final BigDecimal amountOutstanding = null;
    final Boolean penalty = false;
    final Boolean isPaid = null;
    final Boolean isActive = null;
    final Boolean isWaived = null;
    final LocalDate inactivationDate = null;
    final Collection<ClientTransactionData> clientTransactionDatas = null;
    return new ClientChargeData(id, clientId, chargeId, name, chargeTimeType, dueDate, chargeCalculationType, currency, amount, amountPaid, amountWaived, amountWrittenOff, amountOutstanding, penalty, isPaid, isWaived, isActive, inactivationDate, chargeOptions, clientTransactionDatas);
}

38. LoanTransaction#accrueInterest()

View license
public static LoanTransaction accrueInterest(final Office office, final Loan loan, final Money amount, final LocalDate interestAppliedDate, final LocalDateTime createdDate, final AppUser appUser) {
    BigDecimal principalPortion = null;
    BigDecimal feesPortion = null;
    BigDecimal penaltiesPortion = null;
    BigDecimal interestPortion = amount.getAmount();
    BigDecimal overPaymentPortion = null;
    boolean reversed = false;
    PaymentDetail paymentDetail = null;
    String externalId = null;
    return new LoanTransaction(loan, office, LoanTransactionType.ACCRUAL.getValue(), interestAppliedDate.toDate(), interestPortion, principalPortion, interestPortion, feesPortion, penaltiesPortion, overPaymentPortion, reversed, paymentDetail, externalId, createdDate, appUser);
}

39. LoanScheduleModel#toData()

View license
public LoanScheduleData toData() {
    final int decimalPlaces = this.totalPrincipalDisbursed.getCurrencyDigitsAfterDecimal();
    final Integer inMultiplesOf = this.totalPrincipalDisbursed.getCurrencyInMultiplesOf();
    final CurrencyData currency = this.applicationCurrency.toData(decimalPlaces, inMultiplesOf);
    final Collection<LoanSchedulePeriodData> periodsData = new ArrayList<>();
    for (final LoanScheduleModelPeriod modelPeriod : this.periods) {
        periodsData.add(modelPeriod.toData());
    }
    final BigDecimal totalWaived = null;
    final BigDecimal totalWrittenOff = null;
    final BigDecimal totalRepayment = null;
    final BigDecimal totalPaidInAdvance = null;
    final BigDecimal totalPaidLate = null;
    return new LoanScheduleData(currency, periodsData, this.loanTermInDays, this.totalPrincipalDisbursed.getAmount(), this.totalPrincipalExpected, this.totalPrincipalPaid, this.totalInterestCharged, this.totalFeeChargesCharged, this.totalPenaltyChargesCharged, totalWaived, totalWrittenOff, this.totalRepaymentExpected, totalRepayment, totalPaidInAdvance, totalPaidLate, this.totalOutstanding);
}

40. LoanRescheduleModel#toData()

View license
public LoanScheduleData toData() {
    final int decimalPlaces = this.totalPrincipalDisbursed.getCurrencyDigitsAfterDecimal();
    final Integer inMultiplesOf = this.totalPrincipalDisbursed.getCurrencyInMultiplesOf();
    final CurrencyData currency = this.applicationCurrency.toData(decimalPlaces, inMultiplesOf);
    final Collection<LoanSchedulePeriodData> periodsData = new ArrayList<>();
    for (final LoanRescheduleModalPeriod modelPeriod : this.periods) {
        periodsData.add(modelPeriod.toData());
    }
    final BigDecimal totalWaived = null;
    final BigDecimal totalWrittenOff = null;
    final BigDecimal totalRepayment = null;
    final BigDecimal totalPaidInAdvance = null;
    final BigDecimal totalPaidLate = null;
    return new LoanScheduleData(currency, periodsData, this.loanTermInDays, this.totalPrincipalDisbursed.getAmount(), this.totalPrincipalExpected, this.totalPrincipalPaid, this.totalInterestCharged, this.totalFeeChargesCharged, this.totalPenaltyChargesCharged, totalWaived, totalWrittenOff, this.totalRepaymentExpected, totalRepayment, totalPaidInAdvance, totalPaidLate, this.totalOutstanding);
}

41. BigDecimalTest#test_divideLjava_math_BigDecimalI()

Project: j2objc
Source File: BigDecimalTest.java
View license
/**
	 * @tests java.math.BigDecimal#divide(java.math.BigDecimal, int)
	 */
public void test_divideLjava_math_BigDecimalI() {
    BigDecimal divd1 = new BigDecimal(value, 2);
    BigDecimal divd2 = new BigDecimal("2.335");
    BigDecimal divd3 = divd1.divide(divd2, BigDecimal.ROUND_UP);
    assertTrue("123459.08/2.335 is not correct", divd3.toString().equals("52873.27") && divd3.scale() == divd1.scale());
    assertTrue("the unscaledValue representation of 123459.08/2.335 is not correct", divd3.unscaledValue().toString().equals("5287327"));
    divd2 = new BigDecimal(123.4D);
    divd3 = divd1.divide(divd2, BigDecimal.ROUND_DOWN);
    assertTrue("123459.08/123.4  is not correct", divd3.toString().equals("1000.47") && divd3.scale() == 2);
    divd2 = new BigDecimal(000D);
    try {
        divd1.divide(divd2, BigDecimal.ROUND_DOWN);
        fail("divide by zero is not caught");
    } catch (ArithmeticException e) {
    }
}

42. BigDecimalTest#test_divideLjava_math_BigDecimalII()

Project: j2objc
Source File: BigDecimalTest.java
View license
/**
	 * @tests java.math.BigDecimal#divide(java.math.BigDecimal, int, int)
	 */
public void test_divideLjava_math_BigDecimalII() {
    BigDecimal divd1 = new BigDecimal(value2, 4);
    BigDecimal divd2 = new BigDecimal("0.0023");
    BigDecimal divd3 = divd1.divide(divd2, 3, BigDecimal.ROUND_HALF_UP);
    assertTrue("1233456/0.0023 is not correct", divd3.toString().equals("536285217.391") && divd3.scale() == 3);
    divd2 = new BigDecimal(1345.5E-02D);
    divd3 = divd1.divide(divd2, 0, BigDecimal.ROUND_DOWN);
    assertTrue("1233456/13.455 is not correct or does not have the correct scale", divd3.toString().equals("91672") && divd3.scale() == 0);
    divd2 = new BigDecimal(0000D);
    try {
        divd1.divide(divd2, 4, BigDecimal.ROUND_DOWN);
        fail("divide by zero is not caught");
    } catch (ArithmeticException e) {
    }
}

43. BigDecimalTest#test_movePointRightI()

Project: j2objc
Source File: BigDecimalTest.java
View license
/**
	 * @tests java.math.BigDecimal#movePointRight(int)
	 */
public void test_movePointRightI() {
    BigDecimal movePtRight = new BigDecimal("-1.58796521458");
    BigDecimal alreadyMoved = movePtRight.movePointRight(8);
    assertTrue("move point right 8 failed", alreadyMoved.scale() == 3 && alreadyMoved.toString().equals("-158796521.458"));
    movePtRight = new BigDecimal(value, 2);
    alreadyMoved = movePtRight.movePointRight(4);
    assertTrue("move point right 4 failed", alreadyMoved.scale() == 0 && alreadyMoved.toString().equals("1234590800"));
    movePtRight = new BigDecimal(134E12);
    alreadyMoved = movePtRight.movePointRight(2);
    assertTrue("move point right 2 failed", alreadyMoved.scale() == 0 && alreadyMoved.toString().equals("13400000000000000"));
    movePtRight = new BigDecimal(-3.4E-10);
    alreadyMoved = movePtRight.movePointRight(5);
    assertTrue("move point right 5 failed", alreadyMoved.scale() == movePtRight.scale() - 5 && alreadyMoved.doubleValue() == -0.000034);
    alreadyMoved = alreadyMoved.movePointRight(-5);
    assertTrue("move point right -5 failed", alreadyMoved.equals(movePtRight));
}

44. BigDecimalTest#test_scale()

Project: j2objc
Source File: BigDecimalTest.java
View license
/**
	 * @tests java.math.BigDecimal#scale()
	 */
public void test_scale() {
    BigDecimal scale1 = new BigDecimal(value2, 8);
    assertTrue("the scale of the number 123.34560000 is wrong", scale1.scale() == 8);
    BigDecimal scale2 = new BigDecimal("29389.");
    assertTrue("the scale of the number 29389. is wrong", scale2.scale() == 0);
    BigDecimal scale3 = new BigDecimal(3.374E13);
    assertTrue("the scale of the number 3.374E13 is wrong", scale3.scale() == 0);
    BigDecimal scale4 = new BigDecimal("-3.45E-203");
    // note the scale is calculated as 15 digits of 345000.... + exponent -
    // 1. -1 for the 3
    assertTrue("the scale of the number -3.45E-203 is wrong: " + scale4.scale(), scale4.scale() == 205);
    scale4 = new BigDecimal("-345.4E-200");
    assertTrue("the scale of the number -345.4E-200 is wrong", scale4.scale() == 201);
}

45. OrderElement#calculateWorkHoursWithMargin()

Project: libreplan
Source File: OrderElement.java
View license
/**
     * Calculates the work hours with the margin {@link Order#getHoursMargin()}
     * for this orderElement
     *
     * @return calculated work hours
     */
private EffortDuration calculateWorkHoursWithMargin() {
    BigDecimal margin = this.getOrder().getHoursMargin() != null ? new BigDecimal(this.getOrder().getHoursMargin()).setScale(2) : BigDecimal.ZERO;
    BigDecimal hundred = new BigDecimal(100);
    BigDecimal estimatedHours = new BigDecimal(getWorkHours()).setScale(2);
    BigDecimal marginHours = estimatedHours.multiply(margin).divide(hundred, 2, BigDecimal.ROUND_HALF_EVEN);
    BigDecimal result = estimatedHours.add(marginHours);
    return EffortDuration.fromHoursAsBigDecimal(result);
}

46. OrderElement#calculateBudgetWithMargin()

Project: libreplan
Source File: OrderElement.java
View license
/**
     * Calculates the budget with the margin {@link Order#getBudgetMargin()} for
     * this orderElement
     *
     * @return calculated budget
     */
private BigDecimal calculateBudgetWithMargin() {
    BigDecimal margin = this.getOrder().getBudgetMargin() != null ? new BigDecimal(this.getOrder().getBudgetMargin()) : BigDecimal.ZERO;
    BigDecimal hundred = new BigDecimal(100);
    BigDecimal budget = getBudget();
    BigDecimal marginBudget = budget.multiply(margin).divide(hundred, 2, BigDecimal.ROUND_HALF_EVEN);
    return budget.add(marginBudget);
}

47. VariantQuality#getOverallQuality()

Project: Resteasy
Source File: VariantQuality.java
View license
/**
    * @return the quality value between zero and one with five decimal places after the point.
    * @see "3.3 Computing overall quality values"
    */
public BigDecimal getOverallQuality() {
    BigDecimal qt = BigDecimal.valueOf(mediaTypeQualityValue.intValue(), 3);
    BigDecimal qc = BigDecimal.valueOf(characterSetQualityValue.intValue(), 3);
    BigDecimal qe = BigDecimal.valueOf(encodingQualityValue.intValue(), 3);
    BigDecimal ql = BigDecimal.valueOf(languageQualityValue.intValue(), 3);
    assert qt.compareTo(BigDecimal.ZERO) >= 0 && qt.compareTo(BigDecimal.ONE) <= 0;
    assert qc.compareTo(BigDecimal.ZERO) >= 0 && qc.compareTo(BigDecimal.ONE) <= 0;
    assert qe.compareTo(BigDecimal.ZERO) >= 0 && qe.compareTo(BigDecimal.ONE) <= 0;
    assert ql.compareTo(BigDecimal.ZERO) >= 0 && ql.compareTo(BigDecimal.ONE) <= 0;
    BigDecimal result = qt;
    result = result.multiply(qc, MathContext.DECIMAL32);
    result = result.multiply(qe, MathContext.DECIMAL32);
    result = result.multiply(ql, MathContext.DECIMAL32);
    assert result.compareTo(BigDecimal.ZERO) >= 0 && result.compareTo(BigDecimal.ONE) <= 0;
    long round5 = result.scaleByPowerOfTen(5).longValue();
    result = BigDecimal.valueOf(round5, 5);
    assert result.compareTo(BigDecimal.ZERO) >= 0 && result.compareTo(BigDecimal.ONE) <= 0;
    return result;
}

48. SolarEventCalculator#getSunTrueLongitude()

View license
/**
     * Computes the true longitude of the sun, L in the algorithm, at the given location, adjusted to fit in
     * the range [0-360].
     *
     * @param meanAnomaly
     *            the suns mean anomaly.
     * @return the suns true longitude, in <code>BigDecimal</code> form.
     */
private BigDecimal getSunTrueLongitude(BigDecimal meanAnomaly) {
    BigDecimal sinMeanAnomaly = new BigDecimal(Math.sin(convertDegreesToRadians(meanAnomaly).doubleValue()));
    BigDecimal sinDoubleMeanAnomaly = new BigDecimal(Math.sin(multiplyBy(convertDegreesToRadians(meanAnomaly), BigDecimal.valueOf(2)).doubleValue()));
    BigDecimal firstPart = meanAnomaly.add(multiplyBy(sinMeanAnomaly, new BigDecimal("1.916")));
    BigDecimal secondPart = multiplyBy(sinDoubleMeanAnomaly, new BigDecimal("0.020")).add(new BigDecimal("282.634"));
    BigDecimal trueLongitude = firstPart.add(secondPart);
    if (trueLongitude.doubleValue() > 360) {
        trueLongitude = trueLongitude.subtract(BigDecimal.valueOf(360));
    }
    return setScale(trueLongitude);
}

49. BuyZoneModel#sell()

Project: bateman
Source File: BuyZoneModel.java
View license
@Override
public boolean sell(DateTime time, Session session) {
    if (!session.inMarket(time)) {
        return false;
    }
    BigDecimal open = asset.getTimeSeries().openOnDay(time);
    DateTime buyDate = session.lastTrade().getOpen();
    BigDecimal buyPrice = asset.priceAt(buyDate);
    BigDecimal current = asset.priceAt(time);
    BigDecimal difference = current.subtract(buyPrice);
    // exit if at end of day, if our sell trigger threshold is reached,
    // or if we hit our stop loss
    DateTime endOfDay = asset.getTimeSeries().closeOnDay(time);
    boolean atEndOfDay = time.compareTo(endOfDay) >= 0;
    boolean thresholdReached = difference.compareTo(sellTrigger) >= 0;
    boolean stopLossReached = buyPrice.subtract(current).compareTo(stopLoss) >= 0;
    return atEndOfDay || thresholdReached || stopLossReached;
}

50. ClientCharge#calculateOutstanding()

View license
private BigDecimal calculateOutstanding() {
    BigDecimal amountPaidLocal = BigDecimal.ZERO;
    if (this.amountPaid != null) {
        amountPaidLocal = this.amountPaid;
    }
    BigDecimal amountWaivedLocal = BigDecimal.ZERO;
    if (this.amountWaived != null) {
        amountWaivedLocal = this.amountWaived;
    }
    BigDecimal amountWrittenOffLocal = BigDecimal.ZERO;
    if (this.amountWrittenOff != null) {
        amountWrittenOffLocal = this.amountWrittenOff;
    }
    final BigDecimal totalAccountedFor = amountPaidLocal.add(amountWaivedLocal).add(amountWrittenOffLocal);
    return this.amount.subtract(totalAccountedFor);
}

51. LoanCharge#calculateOutstanding()

Project: incubator-fineract
Source File: LoanCharge.java
View license
private BigDecimal calculateOutstanding() {
    if (this.amount == null) {
        return null;
    }
    BigDecimal amountPaidLocal = BigDecimal.ZERO;
    if (this.amountPaid != null) {
        amountPaidLocal = this.amountPaid;
    }
    BigDecimal amountWaivedLocal = BigDecimal.ZERO;
    if (this.amountWaived != null) {
        amountWaivedLocal = this.amountWaived;
    }
    BigDecimal amountWrittenOffLocal = BigDecimal.ZERO;
    if (this.amountWrittenOff != null) {
        amountWrittenOffLocal = this.amountWrittenOff;
    }
    final BigDecimal totalAccountedFor = amountPaidLocal.add(amountWaivedLocal).add(amountWrittenOffLocal);
    return this.amount.subtract(totalAccountedFor);
}

52. LoanInstallmentCharge#calculateOutstanding()

View license
private BigDecimal calculateOutstanding() {
    if (this.amount == null) {
        return null;
    }
    BigDecimal amountPaidLocal = BigDecimal.ZERO;
    if (this.amountPaid != null) {
        amountPaidLocal = this.amountPaid;
    }
    BigDecimal amountWaivedLocal = BigDecimal.ZERO;
    if (this.amountWaived != null) {
        amountWaivedLocal = this.amountWaived;
    }
    BigDecimal amountWrittenOffLocal = BigDecimal.ZERO;
    if (this.amountWrittenOff != null) {
        amountWrittenOffLocal = this.amountWrittenOff;
    }
    final BigDecimal totalAccountedFor = amountPaidLocal.add(amountWaivedLocal).add(amountWrittenOffLocal);
    return this.amount.subtract(totalAccountedFor);
}

53. LoanApplicationTerms#interestRateFor()

View license
public BigDecimal interestRateFor(final PaymentPeriodsInOneYearCalculator calculator, final MathContext mc, final Money outstandingBalance, final LocalDate fromDate, final LocalDate toDate) {
    long loanTermPeriodsInOneYear = calculator.calculate(PeriodFrequencyType.DAYS).longValue();
    int repaymentEvery = Days.daysBetween(fromDate, toDate).getDays();
    if (isFallingInRepaymentPeriod(fromDate, toDate)) {
        loanTermPeriodsInOneYear = calculatePeriodsInOneYear(calculator);
        repaymentEvery = getPeriodsBetween(fromDate, toDate);
    }
    final BigDecimal divisor = BigDecimal.valueOf(Double.valueOf("100.0"));
    final BigDecimal loanTermPeriodsInYearBigDecimal = BigDecimal.valueOf(loanTermPeriodsInOneYear);
    final BigDecimal oneDayOfYearInterestRate = this.annualNominalInterestRate.divide(loanTermPeriodsInYearBigDecimal, mc).divide(divisor, mc);
    BigDecimal interestRate = oneDayOfYearInterestRate.multiply(BigDecimal.valueOf(repaymentEvery), mc);
    return outstandingBalance.getAmount().multiply(interestRate, mc);
}

54. SavingsAccountCharge#calculateOutstanding()

View license
private BigDecimal calculateOutstanding() {
    BigDecimal amountPaidLocal = BigDecimal.ZERO;
    if (this.amountPaid != null) {
        amountPaidLocal = this.amountPaid;
    }
    BigDecimal amountWaivedLocal = BigDecimal.ZERO;
    if (this.amountWaived != null) {
        amountWaivedLocal = this.amountWaived;
    }
    BigDecimal amountWrittenOffLocal = BigDecimal.ZERO;
    if (this.amountWrittenOff != null) {
        amountWrittenOffLocal = this.amountWrittenOff;
    }
    final BigDecimal totalAccountedFor = amountPaidLocal.add(amountWaivedLocal).add(amountWrittenOffLocal);
    return this.amount.subtract(totalAccountedFor);
}

55. ShareAccountCharge#calculateOutstanding()

View license
private BigDecimal calculateOutstanding() {
    BigDecimal amountPaidLocal = BigDecimal.ZERO;
    if (this.amountPaid != null) {
        amountPaidLocal = this.amountPaid;
    }
    BigDecimal amountWaivedLocal = BigDecimal.ZERO;
    if (this.amountWaived != null) {
        amountWaivedLocal = this.amountWaived;
    }
    BigDecimal amountWrittenOffLocal = BigDecimal.ZERO;
    if (this.amountWrittenOff != null) {
        amountWrittenOffLocal = this.amountWrittenOff;
    }
    final BigDecimal totalAccountedFor = amountPaidLocal.add(amountWaivedLocal).add(amountWrittenOffLocal);
    return this.amount.subtract(totalAccountedFor);
}

56. LoanProductRelatedDetailTestHelper#createSettingsForEqualPrincipalAmortizationQuarterly()

View license
public static LoanProductRelatedDetail createSettingsForEqualPrincipalAmortizationQuarterly() {
    final MonetaryCurrency currency = new MonetaryCurrencyBuilder().withCode("USD").withDigitsAfterDecimal(2).build();
    final BigDecimal defaultPrincipal = BigDecimal.valueOf(Double.valueOf("200000"));
    // 2% per month, 24% per year
    final BigDecimal defaultNominalInterestRatePerPeriod = BigDecimal.valueOf(Double.valueOf("2"));
    final PeriodFrequencyType interestPeriodFrequencyType = PeriodFrequencyType.MONTHS;
    final BigDecimal defaultAnnualNominalInterestRate = BigDecimal.valueOf(Double.valueOf("24"));
    final InterestMethod interestMethod = InterestMethod.DECLINING_BALANCE;
    final InterestCalculationPeriodMethod interestCalculationPeriodMethod = InterestCalculationPeriodMethod.SAME_AS_REPAYMENT_PERIOD;
    final Integer repayEvery = Integer.valueOf(3);
    final PeriodFrequencyType repaymentFrequencyType = PeriodFrequencyType.MONTHS;
    final Integer defaultNumberOfRepayments = Integer.valueOf(4);
    final AmortizationMethod amortizationMethod = AmortizationMethod.EQUAL_PRINCIPAL;
    final BigDecimal inArrearsTolerance = BigDecimal.ZERO;
    return createLoanProductRelatedDetail(currency, defaultPrincipal, defaultNominalInterestRatePerPeriod, interestPeriodFrequencyType, defaultAnnualNominalInterestRate, interestMethod, interestCalculationPeriodMethod, repayEvery, repaymentFrequencyType, defaultNumberOfRepayments, amortizationMethod, inArrearsTolerance);
}

57. LoanProductRelatedDetailTestHelper#createSettingsForEqualInstallmentAmortizationQuarterly()

View license
public static LoanProductRelatedDetail createSettingsForEqualInstallmentAmortizationQuarterly() {
    final MonetaryCurrency currency = new MonetaryCurrencyBuilder().withCode("USD").withDigitsAfterDecimal(2).build();
    final BigDecimal defaultPrincipal = BigDecimal.valueOf(Double.valueOf("200000"));
    // 2% per month, 24% per year
    final BigDecimal defaultNominalInterestRatePerPeriod = BigDecimal.valueOf(Double.valueOf("2"));
    final PeriodFrequencyType interestPeriodFrequencyType = PeriodFrequencyType.MONTHS;
    final BigDecimal defaultAnnualNominalInterestRate = BigDecimal.valueOf(Double.valueOf("24"));
    final InterestMethod interestMethod = InterestMethod.DECLINING_BALANCE;
    final InterestCalculationPeriodMethod interestCalculationPeriodMethod = InterestCalculationPeriodMethod.SAME_AS_REPAYMENT_PERIOD;
    final Integer repayEvery = Integer.valueOf(3);
    final PeriodFrequencyType repaymentFrequencyType = PeriodFrequencyType.MONTHS;
    final Integer defaultNumberOfRepayments = Integer.valueOf(4);
    final AmortizationMethod amortizationMethod = AmortizationMethod.EQUAL_INSTALLMENTS;
    final BigDecimal inArrearsTolerance = BigDecimal.ZERO;
    return createLoanProductRelatedDetail(currency, defaultPrincipal, defaultNominalInterestRatePerPeriod, interestPeriodFrequencyType, defaultAnnualNominalInterestRate, interestMethod, interestCalculationPeriodMethod, repayEvery, repaymentFrequencyType, defaultNumberOfRepayments, amortizationMethod, inArrearsTolerance);
}

58. LoanProductRelatedDetailTestHelper#createSettingsForFlatQuarterly()

View license
public static LoanProductRelatedDetail createSettingsForFlatQuarterly(final AmortizationMethod amortizationMethod) {
    final MonetaryCurrency currency = new MonetaryCurrencyBuilder().withCode("USD").withDigitsAfterDecimal(2).build();
    final BigDecimal defaultPrincipal = BigDecimal.valueOf(Double.valueOf("200000"));
    // 2% per month, 24% per year
    final BigDecimal defaultNominalInterestRatePerPeriod = BigDecimal.valueOf(Double.valueOf("2"));
    final PeriodFrequencyType interestPeriodFrequencyType = PeriodFrequencyType.MONTHS;
    final BigDecimal defaultAnnualNominalInterestRate = BigDecimal.valueOf(Double.valueOf("24"));
    final InterestMethod interestMethod = InterestMethod.FLAT;
    final InterestCalculationPeriodMethod interestCalculationPeriodMethod = InterestCalculationPeriodMethod.SAME_AS_REPAYMENT_PERIOD;
    final Integer repayEvery = Integer.valueOf(3);
    final PeriodFrequencyType repaymentFrequencyType = PeriodFrequencyType.MONTHS;
    final Integer defaultNumberOfRepayments = Integer.valueOf(4);
    final BigDecimal inArrearsTolerance = BigDecimal.ZERO;
    return createLoanProductRelatedDetail(currency, defaultPrincipal, defaultNominalInterestRatePerPeriod, interestPeriodFrequencyType, defaultAnnualNominalInterestRate, interestMethod, interestCalculationPeriodMethod, repayEvery, repaymentFrequencyType, defaultNumberOfRepayments, amortizationMethod, inArrearsTolerance);
}

59. LoanProductRelatedDetailTestHelper#createSettingsForIrregularFlatEveryFourMonths()

View license
public static LoanProductRelatedDetail createSettingsForIrregularFlatEveryFourMonths() {
    final MonetaryCurrency currency = new MonetaryCurrencyBuilder().withCode("KSH").withDigitsAfterDecimal(0).build();
    final BigDecimal defaultPrincipal = BigDecimal.valueOf(Double.valueOf("15000"));
    // 2% per month, 24% per year
    final BigDecimal defaultNominalInterestRatePerPeriod = BigDecimal.valueOf(Double.valueOf("2"));
    final PeriodFrequencyType interestPeriodFrequencyType = PeriodFrequencyType.MONTHS;
    final BigDecimal defaultAnnualNominalInterestRate = BigDecimal.valueOf(Double.valueOf("24"));
    final InterestMethod interestMethod = InterestMethod.FLAT;
    final InterestCalculationPeriodMethod interestCalculationPeriodMethod = InterestCalculationPeriodMethod.SAME_AS_REPAYMENT_PERIOD;
    final Integer repayEvery = Integer.valueOf(3);
    final PeriodFrequencyType repaymentFrequencyType = PeriodFrequencyType.MONTHS;
    final Integer defaultNumberOfRepayments = Integer.valueOf(2);
    final BigDecimal inArrearsTolerance = BigDecimal.ZERO;
    final AmortizationMethod amortizationMethod = AmortizationMethod.EQUAL_PRINCIPAL;
    return createLoanProductRelatedDetail(currency, defaultPrincipal, defaultNominalInterestRatePerPeriod, interestPeriodFrequencyType, defaultAnnualNominalInterestRate, interestMethod, interestCalculationPeriodMethod, repayEvery, repaymentFrequencyType, defaultNumberOfRepayments, amortizationMethod, inArrearsTolerance);
}

60. DecimalTest#testDecimalHash()

Project: ion-java
Source File: DecimalTest.java
View license
//=========================================================================
// Test cases
/**
     * Ensure that {@link Decimal#equals} and {@link Decimal#hashCode}
     * are in sync.
     */
@Test
public void testDecimalHash() {
    BigDecimal d1 = new BigDecimal("0.");
    BigDecimal d2 = Decimal.valueOf("0.");
    assertEquals(d1, d2);
    assertEquals("hash code", d1.hashCode(), d2.hashCode());
    d1 = new BigDecimal("0.00");
    d2 = Decimal.valueOf("0.00");
    assertEquals(d1, d2);
    assertEquals("hash code", d1.hashCode(), d2.hashCode());
    // Decimal doesn't override equals() so it negative and positive zeros
    // are equal.  We can't change that since we can't make it symmetric.
    // We must also keep the hash codes the same.
    d1 = new BigDecimal("0.00");
    d2 = Decimal.valueOf("-0.00");
    assertEquals(d1, d2);
    assertEquals("hash code", d1.hashCode(), d2.hashCode());
}

61. BigDecimalTest#test_addLjava_math_BigDecimal()

Project: j2objc
Source File: BigDecimalTest.java
View license
/**
	 * @tests java.math.BigDecimal#add(java.math.BigDecimal)
	 */
public void test_addLjava_math_BigDecimal() {
    BigDecimal add1 = new BigDecimal("23.456");
    BigDecimal add2 = new BigDecimal("3849.235");
    BigDecimal sum = add1.add(add2);
    assertTrue("the sum of 23.456 + 3849.235 is wrong", sum.unscaledValue().toString().equals("3872691") && sum.scale() == 3);
    assertTrue("the sum of 23.456 + 3849.235 is not printed correctly", sum.toString().equals("3872.691"));
    BigDecimal add3 = new BigDecimal(12.34E02D);
    assertTrue("the sum of 23.456 + 12.34E02 is not printed correctly", (add1.add(add3)).toString().equals("1257.456"));
}

62. BigDecimalTest#test_compareToLjava_math_BigDecimal()

Project: j2objc
Source File: BigDecimalTest.java
View license
/**
	 * @tests java.math.BigDecimal#compareTo(java.math.BigDecimal)
	 */
public void test_compareToLjava_math_BigDecimal() {
    BigDecimal comp1 = new BigDecimal("1.00");
    BigDecimal comp2 = new BigDecimal(1.000000D);
    assertTrue("1.00 and 1.000000 should be equal", comp1.compareTo(comp2) == 0);
    BigDecimal comp3 = new BigDecimal("1.02");
    assertTrue("1.02 should be bigger than 1.00", comp3.compareTo(comp1) == 1);
    BigDecimal comp4 = new BigDecimal(0.98D);
    assertTrue("0.98 should be less than 1.00", comp4.compareTo(comp1) == -1);
}

63. BigDecimalTest#test_intValue()

Project: j2objc
Source File: BigDecimalTest.java
View license
/**
	 * @tests java.math.BigDecimal#intValue()
	 */
public void test_intValue() {
    BigDecimal int1 = new BigDecimal(value, 3);
    assertTrue("the int value of 12345.908 is not 12345", int1.intValue() == 12345);
    int1 = new BigDecimal("1.99");
    assertTrue("the int value of 1.99 is not 1", int1.intValue() == 1);
    int1 = new BigDecimal("23423419083091823091283933");
    // ran JDK and found representation for the above was -249268259
    assertTrue("the int value of 23423419083091823091283933 is wrong", int1.intValue() == -249268259);
    int1 = new BigDecimal(-1235D);
    assertTrue("the int value of -1235 is not -1235", int1.intValue() == -1235);
}

64. BigDecimalTest#test_toBigInteger()

Project: j2objc
Source File: BigDecimalTest.java
View license
/**
	 * @tests java.math.BigDecimal#toBigInteger()
	 */
public void test_toBigInteger() {
    BigDecimal sub1 = new BigDecimal("-29830.989");
    BigInteger result = sub1.toBigInteger();
    assertTrue("the bigInteger equivalent of -29830.989 is wrong", result.toString().equals("-29830"));
    sub1 = new BigDecimal(-2837E10);
    result = sub1.toBigInteger();
    assertTrue("the bigInteger equivalent of -2837E10 is wrong", result.doubleValue() == -2837E10);
    sub1 = new BigDecimal(2.349E-10);
    result = sub1.toBigInteger();
    assertTrue("the bigInteger equivalent of 2.349E-10 is wrong", result.equals(BigInteger.ZERO));
    sub1 = new BigDecimal(value2, 6);
    result = sub1.toBigInteger();
    assertTrue("the bigInteger equivalent of 12334.560000 is wrong", result.toString().equals("12334"));
}

65. BigDecimalTest#test_toString()

Project: j2objc
Source File: BigDecimalTest.java
View license
/**
	 * @tests java.math.BigDecimal#toString()
	 */
public void test_toString() {
    BigDecimal toString1 = new BigDecimal("1234.000");
    assertTrue("the toString representation of 1234.000 is wrong", toString1.toString().equals("1234.000"));
    toString1 = new BigDecimal("-123.4E-5");
    assertTrue("the toString representation of -123.4E-5 is wrong: " + toString1, toString1.toString().equals("-0.001234"));
    toString1 = new BigDecimal("-1.455E-20");
    assertTrue("the toString representation of -1.455E-20 is wrong", toString1.toString().equals("-1.455E-20"));
    toString1 = new BigDecimal(value2, 4);
    assertTrue("the toString representation of 1233456.0000 is wrong", toString1.toString().equals("1233456.0000"));
}

66. BigDecimalTest#test_unscaledValue()

Project: j2objc
Source File: BigDecimalTest.java
View license
/**
	 * @tests java.math.BigDecimal#unscaledValue()
	 */
public void test_unscaledValue() {
    BigDecimal unsVal = new BigDecimal("-2839485.000");
    assertTrue("the unscaledValue of -2839485.000 is wrong", unsVal.unscaledValue().toString().equals("-2839485000"));
    unsVal = new BigDecimal(123E10);
    assertTrue("the unscaledValue of 123E10 is wrong", unsVal.unscaledValue().toString().equals("1230000000000"));
    unsVal = new BigDecimal("-4.56E-13");
    assertTrue("the unscaledValue of -4.56E-13 is wrong: " + unsVal.unscaledValue(), unsVal.unscaledValue().toString().equals("-456"));
    unsVal = new BigDecimal(value, 3);
    assertTrue("the unscaledValue of 12345.908 is wrong", unsVal.unscaledValue().toString().equals("12345908"));
}

67. Longs#toBinaryUsingBigDecimal()

View license
public static final String toBinaryUsingBigDecimal(long numberToConvert) {
    long longNumber = numberToConvert;
    if (longNumber < 0)
        throw new IllegalArgumentException("Method argument cannot be negative. number=" + longNumber);
    StringBuilder builder = new StringBuilder();
    BigDecimal zero = new BigDecimal(0);
    BigDecimal two = new BigDecimal(2);
    BigDecimal number = new BigDecimal(longNumber);
    BigDecimal[] decimals = null;
    while (number.compareTo(zero) > 0) {
        decimals = number.divideAndRemainder(two);
        number = decimals[0];
        builder.append(decimals[1]);
    }
    return builder.reverse().toString();
}

68. AddTests#roundAway()

Project: jdk7u-jdk
Source File: AddTests.java
View license
private static int roundAway(BigDecimal b1, BigDecimal b2) {
    int failures = 0;
    b1.precision();
    b2.precision();
    BigDecimal b1_negate = b1.negate();
    BigDecimal b2_negate = b2.negate();
    b1_negate.precision();
    b2_negate.precision();
    failures += roundAway1(b1, b2);
    failures += roundAway1(b1, b2_negate);
    failures += roundAway1(b1_negate, b2);
    failures += roundAway1(b1_negate, b2_negate);
    return failures;
}

69. AddTests#precisionConsistencyTest()

Project: jdk7u-jdk
Source File: AddTests.java
View license
/**
     * Verify calling the precision method should not change the
     * computed result.
     */
private static int precisionConsistencyTest() {
    int failures = 0;
    MathContext mc = new MathContext(1, RoundingMode.DOWN);
    //value is equivalent to 19990
    BigDecimal a = BigDecimal.valueOf(1999, -1);
    BigDecimal sum1 = a.add(BigDecimal.ONE, mc);
    a.precision();
    BigDecimal sum2 = a.add(BigDecimal.ONE, mc);
    if (!sum1.equals(sum2)) {
        failures++;
        System.out.println("Unequal sums after calling precision!");
        System.out.print("Before:\t");
        printAddition(a, BigDecimal.ONE, sum1.toString());
        System.out.print("After:\t");
        printAddition(a, BigDecimal.ONE, sum2.toString());
    }
    return failures;
}

70. InvoiceDaoHelper#computeItemAdjustmentsForTargetInvoiceItem()

Project: killbill
Source File: InvoiceDaoHelper.java
View license
private static void computeItemAdjustmentsForTargetInvoiceItem(final InvoiceItemModelDao targetInvoiceItem, final List<InvoiceItemModelDao> adjustedOrRepairedItems, final Map<UUID, BigDecimal> inputAdjInvoiceItem, final Map<UUID, BigDecimal> outputAdjInvoiceItem) throws InvoiceApiException {
    final BigDecimal originalItemAmount = targetInvoiceItem.getAmount();
    final BigDecimal maxAdjLeftAmount = computeItemAdjustmentAmount(originalItemAmount, adjustedOrRepairedItems);
    final BigDecimal proposedItemAmount = inputAdjInvoiceItem.get(targetInvoiceItem.getId());
    if (proposedItemAmount != null && proposedItemAmount.compareTo(maxAdjLeftAmount) > 0) {
        throw new InvoiceApiException(ErrorCode.INVOICE_ITEM_ADJUSTMENT_AMOUNT_INVALID, proposedItemAmount, maxAdjLeftAmount);
    }
    final BigDecimal itemAmountToAdjust = Objects.firstNonNull(proposedItemAmount, maxAdjLeftAmount);
    if (itemAmountToAdjust.compareTo(BigDecimal.ZERO) > 0) {
        outputAdjInvoiceItem.put(targetInvoiceItem.getId(), itemAmountToAdjust);
    }
}

71. InvoiceDaoHelper#computePositiveRefundAmount()

Project: killbill
Source File: InvoiceDaoHelper.java
View license
public BigDecimal computePositiveRefundAmount(final InvoicePaymentModelDao payment, final BigDecimal requestedRefundAmount, final Map<UUID, BigDecimal> invoiceItemIdsWithAmounts) throws InvoiceApiException {
    final BigDecimal maxRefundAmount = payment.getAmount() == null ? BigDecimal.ZERO : payment.getAmount();
    final BigDecimal requestedPositiveAmount = requestedRefundAmount == null ? maxRefundAmount : requestedRefundAmount;
    // (But that should have been checked in the payment call already)
    if (requestedPositiveAmount.compareTo(maxRefundAmount) > 0) {
        throw new InvoiceApiException(ErrorCode.REFUND_AMOUNT_TOO_HIGH, requestedPositiveAmount, maxRefundAmount);
    }
    // Verify if the requested amount matches the invoice items to adjust, if specified
    BigDecimal amountFromItems = BigDecimal.ZERO;
    for (final BigDecimal itemAmount : invoiceItemIdsWithAmounts.values()) {
        amountFromItems = amountFromItems.add(itemAmount);
    }
    // Sanity check: if some items were specified, then the sum should be equal to specified refund amount, if specified
    if (amountFromItems.compareTo(BigDecimal.ZERO) != 0 && requestedPositiveAmount.compareTo(amountFromItems) < 0) {
        throw new InvoiceApiException(ErrorCode.REFUND_AMOUNT_DONT_MATCH_ITEMS_TO_ADJUST, requestedPositiveAmount, amountFromItems);
    }
    return requestedPositiveAmount;
}

72. AddTests#roundAway()

Project: openjdk
Source File: AddTests.java
View license
private static int roundAway(BigDecimal b1, BigDecimal b2) {
    int failures = 0;
    b1.precision();
    b2.precision();
    BigDecimal b1_negate = b1.negate();
    BigDecimal b2_negate = b2.negate();
    b1_negate.precision();
    b2_negate.precision();
    failures += roundAway1(b1, b2);
    failures += roundAway1(b1, b2_negate);
    failures += roundAway1(b1_negate, b2);
    failures += roundAway1(b1_negate, b2_negate);
    return failures;
}

73. AddTests#precisionConsistencyTest()

Project: openjdk
Source File: AddTests.java
View license
/**
     * Verify calling the precision method should not change the
     * computed result.
     */
private static int precisionConsistencyTest() {
    int failures = 0;
    MathContext mc = new MathContext(1, RoundingMode.DOWN);
    //value is equivalent to 19990
    BigDecimal a = BigDecimal.valueOf(1999, -1);
    BigDecimal sum1 = a.add(BigDecimal.ONE, mc);
    a.precision();
    BigDecimal sum2 = a.add(BigDecimal.ONE, mc);
    if (!sum1.equals(sum2)) {
        failures++;
        System.out.println("Unequal sums after calling precision!");
        System.out.print("Before:\t");
        printAddition(a, BigDecimal.ONE, sum1.toString());
        System.out.print("After:\t");
        printAddition(a, BigDecimal.ONE, sum2.toString());
    }
    return failures;
}

74. VerifiableProperties#getDoubleInRange()

Project: ambry
Source File: VerifiableProperties.java
View license
public Double getDoubleInRange(String name, Double defaultVal, Double start, Double end) {
    Double v = 0.0;
    if (containsKey(name)) {
        v = Double.parseDouble(getProperty(name));
    } else {
        v = defaultVal;
    }
    // use big decimal for double comparison
    BigDecimal startDecimal = new BigDecimal(start);
    BigDecimal endDecimal = new BigDecimal(end);
    BigDecimal value = new BigDecimal(v);
    if (value.compareTo(startDecimal) >= 0 && value.compareTo(endDecimal) <= 0) {
        return v;
    } else {
        throw new IllegalArgumentException(name + " has value " + v + " which is not in range " + start + "-" + end + ".");
    }
}

75. BuyZoneModel#buy()

Project: bateman
Source File: BuyZoneModel.java
View license
@Override
public boolean buy(DateTime time, Session session) {
    if (session.inMarket(time)) {
        return false;
    }
    BigDecimal open = asset.getTimeSeries().openOnDay(time);
    BigDecimal current = asset.priceAt(time);
    BigDecimal increase = current.subtract(open);
    final DateTime midnight = time.toDateMidnight().toDateTime();
    final DateTime nextDay = midnight.plusDays(1);
    boolean tradedToday = (Collections2.filter(session.getTrades(), new Predicate<Trade>() {

        @Override
        public boolean apply(Trade trade) {
            return trade.getOpen().compareTo(midnight) > 0 && trade.getClose().compareTo(nextDay) < 0;
        }
    })).size() > 0;
    return !tradedToday && increase.compareTo(buyTrigger) >= 0;
}

76. BroadleafCurrencyUtils#calculateRemainder()

View license
/**
     * Returns the remainder amount if the passed in totalAmount was divided by the
     * quantity taking into account the normal unit of the currency (e.g. .01 for US).
     * @param currency
     * @return
     */
public static int calculateRemainder(Money totalAmount, int quantity) {
    if (totalAmount == null || totalAmount.isZero() || quantity == 0) {
        return 0;
    }
    // Use this to convert to a whole number (e.g. 1.05 becomes 105 in US currency).
    BigDecimal multiplier = new BigDecimal(10).pow(totalAmount.getAmount().scale());
    BigDecimal amount = totalAmount.getAmount().multiply(multiplier);
    BigDecimal remainder = amount.remainder(new BigDecimal(quantity), ROUND_FLOOR_MATH_CONTEXT);
    return remainder.toBigInteger().intValue();
}

77. ProductBundleComparator#compareSavings()

View license
private int compareSavings(ProductBundle productBundle, ProductBundle productBundle1) {
    BigDecimal savings1 = productBundle.getPotentialSavings();
    BigDecimal savings2 = productBundle1.getPotentialSavings();
    if (savings1 == null && savings2 == null) {
        return 0;
    }
    if (savings1 == null) {
        return savings2.compareTo(BigDecimal.ZERO) * -1;
    }
    if (savings2 == null) {
        return savings1.compareTo(BigDecimal.ZERO);
    }
    return savings1.compareTo(savings2);
}

78. BroadleafCurrencyUtils#calculateRemainder()

View license
/**
     * Returns the remainder amount if the passed in totalAmount was divided by the
     * quantity taking into account the normal unit of the currency (e.g. .01 for US).
     * @param currency
     * @return
     */
public static int calculateRemainder(Money totalAmount, int quantity) {
    if (totalAmount == null || totalAmount.isZero() || quantity == 0) {
        return 0;
    }
    // Use this to convert to a whole number (e.g. 1.05 becomes 105 in US currency).
    BigDecimal multiplier = new BigDecimal(10).pow(totalAmount.getAmount().scale());
    BigDecimal amount = totalAmount.getAmount().multiply(multiplier);
    BigDecimal remainder = amount.remainder(new BigDecimal(quantity), ROUND_FLOOR_MATH_CONTEXT);
    return remainder.toBigInteger().intValue();
}

79. ProductBundleComparator#compareSavings()

View license
private int compareSavings(ProductBundle productBundle, ProductBundle productBundle1) {
    BigDecimal savings1 = productBundle.getPotentialSavings();
    BigDecimal savings2 = productBundle1.getPotentialSavings();
    if (savings1 == null && savings2 == null) {
        return 0;
    }
    if (savings1 == null) {
        return savings2.compareTo(BigDecimal.ZERO) * -1;
    }
    if (savings2 == null) {
        return savings1.compareTo(BigDecimal.ZERO);
    }
    return savings1.compareTo(savings2);
}

80. MaxValidatorForDouble#isValid()

Project: disconf
Source File: MaxValidatorForDouble.java
View license
public boolean isValid(Double value, ConstraintValidatorContext constraintValidatorContext) {
    // null values are valid
    if (value == null) {
        return true;
    }
    BigDecimal premium = BigDecimal.valueOf(value);
    BigDecimal netToCompany = BigDecimal.valueOf(maxValue);
    BigDecimal commission = premium.subtract(netToCompany);
    return commission.compareTo(BigDecimal.ZERO) <= 0;
}

81. MinValidatorForDouble#isValid()

Project: disconf
Source File: MinValidatorForDouble.java
View license
public boolean isValid(Double value, ConstraintValidatorContext constraintValidatorContext) {
    // null values are valid
    if (value == null) {
        return true;
    }
    BigDecimal premium = BigDecimal.valueOf(value);
    BigDecimal netToCompany = BigDecimal.valueOf(minValue);
    BigDecimal commission = premium.subtract(netToCompany);
    return commission.compareTo(BigDecimal.ZERO) >= 0;
}

82. FinanceHelper#buildFqSettlementAmount()

Project: fqms
Source File: FinanceHelper.java
View license
/**
     * ????????
     *
     * @param financeParentOrder
     * @return
     */
public void buildFqSettlementAmount(FinanceParentOrder financeParentOrder) {
    BigDecimal fqSettlementAmount = BigDecimal.ZERO;
    // ?????????
    BigDecimal channelSettlementAmount = financeParentOrder.getChannelSettlementAmount();
    // ????????
    BigDecimal innSettlementAmount = financeParentOrder.getInnSettlementAmount();
    if (channelSettlementAmount != null && innSettlementAmount != null) {
        // ??????????????-??????
        fqSettlementAmount = channelSettlementAmount.subtract(innSettlementAmount);
    }
    financeParentOrder.setFqSettlementAmount(fqSettlementAmount);
}

83. TestVoltDecimalHelper#testSerializatinRoundTrip()

Project: h-store
Source File: TestVoltDecimalHelper.java
View license
public void testSerializatinRoundTrip() throws Exception {
    BigDecimal bd = new BigDecimal("7654321");
    ByteBuffer buf = ByteBuffer.allocate(100);
    VoltDecimalHelper.serializeBigDecimal(bd, buf);
    buf.flip();
    BigDecimal bd2 = VoltDecimalHelper.deserializeBigDecimal(buf);
    System.out.println(bd.toString());
    System.out.println(bd2.toString());
    int cmp = bd.compareTo(bd2);
    assertEquals(0, cmp);
    FastSerializer fs = new FastSerializer();
    VoltDecimalHelper.serializeBigDecimal(bd, fs);
    BigDecimal bd3 = VoltDecimalHelper.deserializeBigDecimal(fs.getBuffer());
    System.out.println(bd.toString());
    System.out.println(bd3.toString());
    cmp = bd.compareTo(bd3);
    assertEquals(0, cmp);
}

84. TestVoltDecimalHelper#testSerializatinRoundTripNegative()

Project: h-store
Source File: TestVoltDecimalHelper.java
View license
public void testSerializatinRoundTripNegative() throws Exception {
    BigDecimal bd = new BigDecimal("-23325.23425");
    ByteBuffer buf = ByteBuffer.allocate(100);
    VoltDecimalHelper.serializeBigDecimal(bd, buf);
    buf.flip();
    BigDecimal bd2 = VoltDecimalHelper.deserializeBigDecimal(buf);
    System.out.println(bd.toString());
    System.out.println(bd2.toString());
    int cmp = bd.compareTo(bd2);
    assertEquals(0, cmp);
    FastSerializer fs = new FastSerializer();
    VoltDecimalHelper.serializeBigDecimal(bd, fs);
    BigDecimal bd3 = VoltDecimalHelper.deserializeBigDecimal(fs.getBuffer());
    System.out.println(bd.toString());
    System.out.println(bd3.toString());
    cmp = bd.compareTo(bd3);
    assertEquals(0, cmp);
}

85. Charge#fromJson()

Project: incubator-fineract
Source File: Charge.java
View license
public static Charge fromJson(final JsonCommand command, final GLAccount account, final TaxGroup taxGroup) {
    final String name = command.stringValueOfParameterNamed("name");
    final BigDecimal amount = command.bigDecimalValueOfParameterNamed("amount");
    final String currencyCode = command.stringValueOfParameterNamed("currencyCode");
    final ChargeAppliesTo chargeAppliesTo = ChargeAppliesTo.fromInt(command.integerValueOfParameterNamed("chargeAppliesTo"));
    final ChargeTimeType chargeTimeType = ChargeTimeType.fromInt(command.integerValueOfParameterNamed("chargeTimeType"));
    final ChargeCalculationType chargeCalculationType = ChargeCalculationType.fromInt(command.integerValueOfParameterNamed("chargeCalculationType"));
    final Integer chargePaymentMode = command.integerValueOfParameterNamed("chargePaymentMode");
    final ChargePaymentMode paymentMode = chargePaymentMode == null ? null : ChargePaymentMode.fromInt(chargePaymentMode);
    final boolean penalty = command.booleanPrimitiveValueOfParameterNamed("penalty");
    final boolean active = command.booleanPrimitiveValueOfParameterNamed("active");
    final MonthDay feeOnMonthDay = command.extractMonthDayNamed("feeOnMonthDay");
    final Integer feeInterval = command.integerValueOfParameterNamed("feeInterval");
    final BigDecimal minCap = command.bigDecimalValueOfParameterNamed("minCap");
    final BigDecimal maxCap = command.bigDecimalValueOfParameterNamed("maxCap");
    final Integer feeFrequency = command.integerValueOfParameterNamed("feeFrequency");
    return new Charge(name, amount, currencyCode, chargeAppliesTo, chargeTimeType, chargeCalculationType, penalty, active, paymentMode, feeOnMonthDay, feeInterval, minCap, maxCap, feeFrequency, account, taxGroup);
}

86. InterestRateChartSlabData#template()

View license
public static InterestRateChartSlabData template(final Collection<EnumOptionData> periodTypes, final Collection<EnumOptionData> entityTypeOptions, final Collection<EnumOptionData> attributeNameOptions, final Collection<EnumOptionData> conditionTypeOptions, final Collection<EnumOptionData> incentiveTypeOptions, final Collection<CodeValueData> genderOptions, final Collection<CodeValueData> clientTypeOptions, final Collection<CodeValueData> clientClassificationOptions) {
    final Long id = null;
    final String description = null;
    final EnumOptionData periodType = null;
    final Integer fromPeriod = null;
    final Integer toPeriod = null;
    final BigDecimal amountRangeFrom = null;
    final BigDecimal amountRangeTo = null;
    final BigDecimal annualInterestRate = null;
    final CurrencyData currency = null;
    final Set<InterestIncentiveData> incentivesData = null;
    return new InterestRateChartSlabData(id, description, periodType, fromPeriod, toPeriod, amountRangeFrom, amountRangeTo, annualInterestRate, currency, incentivesData, periodTypes, entityTypeOptions, attributeNameOptions, conditionTypeOptions, incentiveTypeOptions, genderOptions, clientTypeOptions, clientClassificationOptions);
}

87. InterestRateChartSlabAssembler#assembleChartSlabs()

View license
private InterestRateChartSlab assembleChartSlabs(final InterestRateChart interestRateChart, final JsonElement element, final String currencyCode, final Locale locale) {
    final String description = this.fromApiJsonHelper.extractStringNamed(descriptionParamName, element);
    final Integer periodTypeId = this.fromApiJsonHelper.extractIntegerNamed(periodTypeParamName, element, locale);
    final SavingsPeriodFrequencyType periodType = SavingsPeriodFrequencyType.fromInt(periodTypeId);
    final Integer fromPeriod = this.fromApiJsonHelper.extractIntegerNamed(fromPeriodParamName, element, locale);
    final Integer toPeriod = this.fromApiJsonHelper.extractIntegerNamed(toPeriodParamName, element, locale);
    final BigDecimal amountRangeFrom = this.fromApiJsonHelper.extractBigDecimalNamed(amountRangeFromParamName, element, locale);
    final BigDecimal amountRangeTo = this.fromApiJsonHelper.extractBigDecimalNamed(amountRangeToParamName, element, locale);
    final BigDecimal annualInterestRate = this.fromApiJsonHelper.extractBigDecimalNamed(annualInterestRateParamName, element, locale);
    final InterestRateChartSlabFields slabFields = InterestRateChartSlabFields.createNew(description, periodType, fromPeriod, toPeriod, amountRangeFrom, amountRangeTo, annualInterestRate, currencyCode);
    InterestRateChartSlab interestRateChartSlab = InterestRateChartSlab.createNew(slabFields, interestRateChart);
    this.incentiveAssembler.assembleIncentivesFrom(element, interestRateChartSlab, locale);
    return interestRateChartSlab;
}

88. Loan#recalculateLoanCharge()

Project: incubator-fineract
Source File: Loan.java
View license
private void recalculateLoanCharge(final LoanCharge loanCharge, final int penaltyWaitPeriod) {
    BigDecimal amount = BigDecimal.ZERO;
    BigDecimal chargeAmt = BigDecimal.ZERO;
    BigDecimal totalChargeAmt = BigDecimal.ZERO;
    if (loanCharge.getChargeCalculation().isPercentageBased()) {
        if (loanCharge.isOverdueInstallmentCharge()) {
            amount = calculateOverdueAmountPercentageAppliedTo(loanCharge, penaltyWaitPeriod);
        } else {
            amount = calculateAmountPercentageAppliedTo(loanCharge);
        }
        chargeAmt = loanCharge.getPercentage();
        if (loanCharge.isInstalmentFee()) {
            totalChargeAmt = calculatePerInstallmentChargeAmount(loanCharge);
        }
    } else {
        chargeAmt = loanCharge.amountOrPercentage();
    }
    if (loanCharge.isActive()) {
        loanCharge.update(chargeAmt, loanCharge.getDueLocalDate(), amount, fetchNumberOfInstallmensAfterExceptions(), totalChargeAmt);
        validateChargeHasValidSpecifiedDateIfApplicable(loanCharge, getDisbursementDate(), getLastRepaymentPeriodDueDate(false));
    }
}

89. Loan#determineCumulativeIncomeFromInstallments()

Project: incubator-fineract
Source File: Loan.java
View license
private void determineCumulativeIncomeFromInstallments(HashMap<String, BigDecimal> cumulativeIncomeFromInstallments) {
    BigDecimal interest = BigDecimal.ZERO;
    BigDecimal fee = BigDecimal.ZERO;
    BigDecimal penalty = BigDecimal.ZERO;
    List<LoanRepaymentScheduleInstallment> installments = getRepaymentScheduleInstallments();
    for (LoanRepaymentScheduleInstallment installment : installments) {
        interest = interest.add(installment.getInterestCharged(getCurrency()).getAmount());
        fee = fee.add(installment.getFeeChargesCharged(getCurrency()).getAmount());
        penalty = penalty.add(installment.getPenaltyChargesCharged(getCurrency()).getAmount());
    }
    cumulativeIncomeFromInstallments.put("interest", interest);
    cumulativeIncomeFromInstallments.put("fee", fee);
    cumulativeIncomeFromInstallments.put("penalty", penalty);
}

90. Loan#determineCumulativeIncomeDetails()

Project: incubator-fineract
Source File: Loan.java
View license
private void determineCumulativeIncomeDetails(Collection<LoanTransaction> transactions, HashMap<String, BigDecimal> incomeDetailsMap) {
    BigDecimal interest = BigDecimal.ZERO;
    BigDecimal fee = BigDecimal.ZERO;
    BigDecimal penalty = BigDecimal.ZERO;
    for (LoanTransaction transaction : transactions) {
        interest = interest.add(transaction.getInterestPortion(getCurrency()).getAmount());
        fee = fee.add(transaction.getFeeChargesPortion(getCurrency()).getAmount());
        penalty = penalty.add(transaction.getPenaltyChargesPortion(getCurrency()).getAmount());
    }
    incomeDetailsMap.put("interest", interest);
    incomeDetailsMap.put("fee", fee);
    incomeDetailsMap.put("penalty", penalty);
}

91. LoanApplicationTerms#calculateFlatInterestRateForLoanTerm()

View license
private BigDecimal calculateFlatInterestRateForLoanTerm(final PaymentPeriodsInOneYearCalculator calculator, final MathContext mc) {
    final BigDecimal divisor = BigDecimal.valueOf(Double.valueOf("100.0"));
    final long loanTermPeriodsInOneYear = calculatePeriodsInOneYear(calculator);
    final BigDecimal loanTermPeriodsInYearBigDecimal = BigDecimal.valueOf(loanTermPeriodsInOneYear);
    final BigDecimal loanTermFrequencyBigDecimal = calculatePeriodsInLoanTerm();
    return this.annualNominalInterestRate.divide(loanTermPeriodsInYearBigDecimal, mc).divide(divisor, mc).multiply(loanTermFrequencyBigDecimal);
}

92. DepositProductAssembler#assembleDepositAmountDetails()

View license
public DepositProductAmountDetails assembleDepositAmountDetails(final JsonCommand command) {
    BigDecimal minDepositAmount = null;
    if (command.parameterExists(depositMinAmountParamName)) {
        minDepositAmount = command.bigDecimalValueOfParameterNamed(depositMinAmountParamName);
    }
    BigDecimal maxDepositAmount = null;
    if (command.parameterExists(depositMaxAmountParamName)) {
        maxDepositAmount = command.bigDecimalValueOfParameterNamed(depositMaxAmountParamName);
    }
    BigDecimal depositAmount = null;
    if (command.parameterExists(depositAmountParamName)) {
        depositAmount = command.bigDecimalValueOfParameterNamed(depositAmountParamName);
    }
    final DepositProductAmountDetails depositRecurringDetail = new DepositProductAmountDetails(minDepositAmount, depositAmount, maxDepositAmount);
    return depositRecurringDetail;
}

93. RecurringDepositScheduleInstallment#installment()

View license
public static RecurringDepositScheduleInstallment installment(final RecurringDepositAccount account, final Integer installmentNumber, final Date dueDate, final BigDecimal depositAmount) {
    final Date fromDate = null;
    final BigDecimal depositAmountCompleted = null;
    final BigDecimal totalPaidInAdvance = null;
    final BigDecimal totalPaidLate = null;
    final boolean obligationsMet = false;
    final Date obligationsMetOnDate = null;
    return new RecurringDepositScheduleInstallment(account, installmentNumber, fromDate, dueDate, depositAmount, depositAmountCompleted, totalPaidInAdvance, totalPaidLate, obligationsMet, obligationsMetOnDate);
}

94. Timestamp#compareTo()

Project: ion-java
Source File: Timestamp.java
View license
/**
     * Performs a comparison of the two points in time represented by two
     * Timestamps.
     * If the point in time represented by this Timestamp precedes that of
     * {@code t}, then {@code -1} is returned.
     * If {@code t} precedes this Timestamp then {@code 1} is returned.
     * If the Timestamps represent the same point in time, then
     * {@code 0} is returned.
     * Note that a {@code 0} result does not imply that the two Timestamps are
     * {@link #equals}, as the local offset or precision of the two Timestamps
     * may be different.
     *
     * <p>
     * This method is provided in preference to individual methods for each of
     * the six boolean comparison operators (<, ==, >, >=, !=, <=).
     * The suggested idiom for performing these comparisons is:
     * {@code (x.compareTo(y)}<em><op></em>{@code 0)},
     * where <em><op></em> is one of the six comparison operators.
     *
     * <p>
     * For example, the pairs below will return a {@code 0} result:
     * <ul>
     *   <li>{@code 2009T}</li>
     *   <li>{@code 2009-01T}</li>
     *   <li>{@code 2009-01-01T}</li>
     *   <li>{@code 2009-01-01T00:00Z}</li>
     *   <li>{@code 2009-01-01T00:00:00Z}</li>
     *   <li>{@code 2009-01-01T00:00:00.0Z}</li>
     *   <li>{@code 2009-01-01T00:00:00.00Z}</li>
     *
     *   <li>{@code 2008-12-31T16:00-08:00}</li>
     *   <li>{@code 2008-12-31T12:00-12:00}</li>
     *   <li>{@code 2009-01-01T12:00+12:00}</li>
     * </ul>
     *
     * <p>
     * Use the {@link #equals(Timestamp)} method to compare the point
     * in time, <em>including</em> precision and local offset.
     *
     * @param t
     *          the other {@code Timestamp} to compare this {@code Timestamp} to
     *
     * @return
     *          -1, 0, or 1 if this {@code Timestamp}
     *          is less than, equal to, or greater than {@code t} respectively
     *
     * @throws NullPointerException if {@code t} is null.
     *
     * @see #equals(Timestamp)
     */
public int compareTo(Timestamp t) {
    // Test at millisecond precision first.
    long this_millis = this.getMillis();
    long arg_millis = t.getMillis();
    if (this_millis != arg_millis) {
        return (this_millis < arg_millis) ? -1 : 1;
    }
    // Values are equivalent at millisecond precision, so compare fraction
    BigDecimal this_fraction = ((this._fraction == null) ? BigDecimal.ZERO : this._fraction);
    BigDecimal arg_fraction = ((t._fraction == null) ? BigDecimal.ZERO : t._fraction);
    return this_fraction.compareTo(arg_fraction);
}

95. ExecutionParametersTest#roundTripBigDecimal()

Project: isis
Source File: ExecutionParametersTest.java
View license
@Test
public void roundTripBigDecimal() throws Exception {
    // given
    final BigDecimal value = new BigDecimal("123456.789123456789");
    // when
    executionParameters.setParameter("test", value);
    final BigDecimal roundTripped = executionParameters.getParameterAsBigDecimal("test");
    final BigDecimal roundTrippedAsT = executionParameters.getParameterAsT("test", BigDecimal.class);
    // then
    assertThat(roundTripped, is(value));
    assertThat(roundTrippedAsT, is(value));
}

96. BigDecimalArithmeticTest#testAddEqualScalePosPos()

View license
/**
     * Add two numbers of equal positive scales
     */
public void testAddEqualScalePosPos() {
    String a = "1231212478987482988429808779810457634781384756794987";
    int aScale = 10;
    String b = "747233429293018787918347987234564568";
    int bScale = 10;
    String c = "123121247898748373566323807282924555312937.1991359555";
    int cScale = 10;
    BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale);
    BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale);
    BigDecimal result = aNumber.add(bNumber);
    assertEquals("incorrect value", c, result.toString());
    assertEquals("incorrect scale", cScale, result.scale());
}

97. BigDecimalArithmeticTest#testAddMathContextEqualScalePosPos()

View license
/**
     * Add two numbers of equal positive scales using MathContext
     */
public void testAddMathContextEqualScalePosPos() {
    String a = "1231212478987482988429808779810457634781384756794987";
    int aScale = 10;
    String b = "747233429293018787918347987234564568";
    int bScale = 10;
    String c = "1.2313E+41";
    int cScale = -37;
    BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale);
    BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale);
    MathContext mc = new MathContext(5, RoundingMode.UP);
    BigDecimal result = aNumber.add(bNumber, mc);
    assertEquals("incorrect value", c, result.toString());
    assertEquals("incorrect scale", cScale, result.scale());
}

98. BigDecimalArithmeticTest#testAddEqualScaleNegNeg()

View license
/**
     * Add two numbers of equal negative scales
     */
public void testAddEqualScaleNegNeg() {
    String a = "1231212478987482988429808779810457634781384756794987";
    int aScale = -10;
    String b = "747233429293018787918347987234564568";
    int bScale = -10;
    String c = "1.231212478987483735663238072829245553129371991359555E+61";
    int cScale = -10;
    BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale);
    BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale);
    BigDecimal result = aNumber.add(bNumber);
    assertEquals("incorrect value", c, result.toString());
    assertEquals("incorrect scale", cScale, result.scale());
}

99. BigDecimalArithmeticTest#testAddMathContextEqualScaleNegNeg()

View license
/**
     * Add two numbers of equal negative scales using MathContext
     */
public void testAddMathContextEqualScaleNegNeg() {
    String a = "1231212478987482988429808779810457634781384756794987";
    int aScale = -10;
    String b = "747233429293018787918347987234564568";
    int bScale = -10;
    String c = "1.2312E+61";
    int cScale = -57;
    BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale);
    BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale);
    MathContext mc = new MathContext(5, RoundingMode.FLOOR);
    BigDecimal result = aNumber.add(bNumber, mc);
    assertEquals("incorrect value ", c, result.toString());
    assertEquals("incorrect scale", cScale, result.scale());
}

100. BigDecimalArithmeticTest#testAddDiffScalePosNeg()

View license
/**
     * Add two numbers of different scales; the first is positive
     */
public void testAddDiffScalePosNeg() {
    String a = "1231212478987482988429808779810457634781384756794987";
    int aScale = 15;
    String b = "747233429293018787918347987234564568";
    int bScale = -10;
    String c = "7472334294161400358170962860775454459810457634.781384756794987";
    int cScale = 15;
    BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale);
    BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale);
    BigDecimal result = aNumber.add(bNumber);
    assertEquals("incorrect value", c, result.toString());
    assertEquals("incorrect scale", cScale, result.scale());
}