@Test public void testAddTradeOrder() { try { String side = this.tradestrategy.getSide(); String action = Action.BUY; if (Side.SLD.equals(side)) { action = Action.SELL; } double risk = this.tradestrategy.getRiskAmount().doubleValue(); double stop = 0.20; BigDecimal price = new BigDecimal(20); int quantity = (int) ((int) risk / stop); ZonedDateTime createDate = this.tradestrategy.getTradingday().getOpen().plusMinutes(5); TradeOrder tradeOrder = new TradeOrder( this.tradestrategy, action, OrderType.STPLMT, quantity, price, price.add(new BigDecimal(0.004)), TradingCalendar.getDateTimeNowMarketTimeZone()); tradeOrder.setOrderKey((new BigDecimal((Math.random() * 1000000))).intValue()); tradeOrder.setClientId(clientId); tradeOrder.setTransmit(true); tradeOrder.setStatus("SUBMITTED"); tradeOrder.validate(); tradeOrder = tradeOrderHome.persist(tradeOrder); assertNotNull("1", tradeOrder); _log.info("IdOrder: " + tradeOrder.getIdTradeOrder()); TradeOrder tradeOrder1 = new TradeOrder( this.tradestrategy, Action.SELL, OrderType.STP, quantity, price.subtract(new BigDecimal(1)), null, createDate); tradeOrder1.setAuxPrice(price.subtract(new BigDecimal(1))); tradeOrder1.setOrderKey((new BigDecimal((Math.random() * 1000000))).intValue()); tradeOrder1.setClientId(clientId); tradeOrder1.setTransmit(true); tradeOrder1.setStatus("SUBMITTED"); tradeOrder1.validate(); tradeOrder1 = tradeOrderHome.persist(tradeOrder1); assertNotNull("2", tradeOrder1); } catch (Exception | AssertionError ex) { String msg = "Error running " + name.getMethodName() + " msg: " + ex.getMessage(); _log.error(msg); fail(msg); } }
public void calculator() { BigDecimal bg1 = new BigDecimal(this.firstNum); BigDecimal bg2 = new BigDecimal(this.secondNum); switch (this.oprator) { case '+': this.result = bg1.add(bg2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); break; case '-': this.result = bg1.subtract(bg2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); break; case '*': this.result = bg1.multiply(bg2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); break; case '/': if (bg2.subtract(new BigDecimal(0)).doubleValue() > 0 || bg2.subtract(new BigDecimal(0)).doubleValue() < 0) { this.result = bg1.divide(bg2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); } else { throw new RuntimeException("被除数不能为0"); } break; default: throw new RuntimeException("操作符必须为+-*/"); } }
public BigDecimal doBalance( ClaimPayPlan claimPayPlan, Long p2pPrepaidAccount, Investment investment, Long p2pPfAccount) { // 误差调整 // 投资人利息罚息总和 BigDecimal sumGatherInterest = claimGatherPlanRepository.sumInterestByInvSeqAndPeriod( claimPayPlan.getInvestmentSequence(), claimPayPlan.getClaimPayPlanNumber()); // 借款人利息罚息总和 BigDecimal sumPayInterest = claimPayPlan .getClaimPayPlanTotalAmount() .add(claimPayPlan.getClaimPayPlanJusticeInterest()); BigDecimal pmFee = claimPayPlan.getClaimPayPlanPlatformManagementFee(); BigDecimal balance = BigDecimal.ZERO; // 利息罚息尾数误差处理 if (sumPayInterest.compareTo(sumGatherInterest) > 0) { balance = sumPayInterest.subtract(sumGatherInterest); pmFee = pmFee.add(balance); creBalanceOrder(claimPayPlan, investment, pmFee, p2pPrepaidAccount, p2pPfAccount); } else if (sumPayInterest.compareTo(sumGatherInterest) < 0) { balance = sumGatherInterest.subtract(sumPayInterest); pmFee = pmFee.subtract(balance); creBalanceOrder(claimPayPlan, investment, pmFee, p2pPfAccount, p2pPrepaidAccount); } return pmFee; }
/** * Creates functional bins (bins actually used for the binning, not shown to the user) which are * be bumped out by one CUV to allow for rounding errors if they are too close to the actual min * and max values. * * <p>For instance, if the top post is 50 and the actual max value is 49.9999, the functional top * post would be bumped to 50.01 if the cuv is .01. * * @param posts * @param actualMin * @param actualMin * @param characteristicUnitValue * @return */ public static BigDecimal[] createFunctionalPosts( BigDecimal[] posts, BigDecimal actualMin, BigDecimal actualMax, BigDecimal characteristicUnitValue) { BigDecimal roundErrThreshold = new BigDecimal(".0001"); roundErrThreshold = roundErrThreshold.min(characteristicUnitValue); // Start with the original top and bottom values BigDecimal min = posts[0]; BigDecimal max = posts[posts.length - 1]; if (actualMin.subtract(min).compareTo(roundErrThreshold) < 0) { min = min.subtract(characteristicUnitValue); } if (max.subtract(actualMax).compareTo(roundErrThreshold) < 0) { max = max.add(characteristicUnitValue); } BigDecimal[] functional = Arrays.copyOf(posts, posts.length); functional[0] = min; functional[posts.length - 1] = max; return functional; }
/** * BankStmt - Amount. Calculate ChargeAmt = StmtAmt - TrxAmt - InterestAmt or id Charge is entered * - InterestAmt = StmtAmt - TrxAmt - ChargeAmt * * @param ctx context * @param WindowNo window no * @param mTab tab * @param mField field * @param value value * @return null or error message */ public String amount(Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value) { if (isCalloutActive()) return ""; // Get Stmt & Trx BigDecimal stmt = (BigDecimal) mTab.getValue("StmtAmt"); if (stmt == null) stmt = Env.ZERO; BigDecimal trx = (BigDecimal) mTab.getValue("TrxAmt"); if (trx == null) trx = Env.ZERO; BigDecimal bd = stmt.subtract(trx); // Charge - calculate Interest if (mField.getColumnName().equals("ChargeAmt")) { BigDecimal charge = (BigDecimal) value; if (charge == null) charge = Env.ZERO; bd = bd.subtract(charge); // log.trace(log.l5_DData, "Interest (" + bd + ") = Stmt(" + stmt + ") - Trx(" + trx + ") - // Charge(" + charge + ")"); mTab.setValue("InterestAmt", bd); } // Calculate Charge else { BigDecimal interest = (BigDecimal) mTab.getValue("InterestAmt"); if (interest == null) interest = Env.ZERO; bd = bd.subtract(interest); // log.trace(log.l5_DData, "Charge (" + bd + ") = Stmt(" + stmt + ") - Trx(" + trx + ") - // Interest(" + interest + ")"); mTab.setValue("ChargeAmt", bd); } return ""; } // amount
@GET @Path("review") public Response getSalesOrder( @QueryParam("callback") String callback, @QueryParam("promoCode") String promoCode, @QueryParam("zipCode") Integer zipCode, @QueryParam("subTotal") BigDecimal subTotal) { Response response = null; BigDecimal discount = discountCalculator.getDiscount(promoCode); BigDecimal taxAmount = taxCalculator.getTaxRate(zipCode).multiply((subTotal.subtract(discount))); BigDecimal shippingAmount = shippingCalculator.getShippingCost(zipCode, subTotal); Map<String, BigDecimal> keyValues = new HashMap(); keyValues.put("discount", discount); keyValues.put("salesTax", taxAmount); keyValues.put("shipping", shippingAmount); keyValues.put("total", subTotal.subtract(discount).add(taxAmount).add(shippingAmount)); response = Response.status(Status.OK).entity(keyValues).build(); // response.getHeaders().add("Access-Control-Allow-Origin", "http://localhost:8090"); // response.getHeaders().add("Content-Type", "application/json"); // response.getHeaders().add("X-Served-By", "MyStoreJEE"); return response; }
// Gauss-Legendre Algorithm public static BigDecimal calculatePi() { BigDecimal a = ONE; BigDecimal b = ONE.divide(sqrt(TWO, SCALE), SCALE, BigDecimal.ROUND_HALF_UP); BigDecimal t = new BigDecimal(0.25); BigDecimal x = ONE; BigDecimal y; while (!a.equals(b)) { y = a; // a = (a + b)/2 a = a.add(b).divide(TWO, SCALE, BigDecimal.ROUND_HALF_UP); // b = sqrt(b*y) b = sqrt(b.multiply(y), SCALE); // t -= x*((y - a)^2) t = t.subtract(x.multiply(y.subtract(a).multiply(y.subtract(a)))); // x *= 2 x = x.multiply(TWO); } // a + (a+b)/(4) return a.add(b).multiply(a.add(b)).divide(t.multiply(FOUR), SCALE, BigDecimal.ROUND_HALF_UP); }
private int start(int rounding, int iterations) { BigDecimal three = new BigDecimal("3"); BigDecimal two = new BigDecimal("2"); MathContext division = new MathContext((int) Math.round(rounding), RoundingMode.HALF_UP); BigDecimal x0 = new BigDecimal("5.0"); BigDecimal x1 = new BigDecimal("5.0"); for (int i = 0; i < iterations; i++) { /*x1 = x0.pow(2); System.out.println("1: " + x1.toPlainString()); x1 = x1.subtract(three); System.out.println("2: " + x1.toPlainString()); x1 = x1.divide(x0.multiply(two), division); System.out.println("3: " + x1.toPlainString()); x0 = x0.subtract(x1); System.out.println("x0: " + x1.toPlainString());*/ x1 = x0.subtract((x0.pow(2).subtract(three)).divide(x0.multiply(two), division)); x0 = x1; // if(i % 10 == 0) { System.out.println(i); } } String digits1 = x1.toString(); x1 = x0.subtract((x0.pow(2).subtract(three)).divide(x0.multiply(two), division)); x0 = x1; String digits2 = x1.toString(); // System.out.println("Sqrt(3) = " + x1.toPlainString()); return checkDigits(digits1, digits2); }
// 密码加密 private static String Encryption(String oldPwd) { String newPwd = "0"; BigDecimal oldPwdBD = new BigDecimal(oldPwd); BigDecimal tempYPwd = oldPwdBD.multiply(new BigDecimal("135791")); int tempYPwdLen = tempYPwd.toString().length(); String tempTPwd = ""; if (tempYPwdLen >= 12) { tempTPwd = tempYPwd.toString().substring(1, 7); } else if (tempYPwdLen < 12 && tempYPwdLen >= 5) { tempTPwd = tempYPwd.toString().substring(0, tempYPwd.toString().length() - 5); } else { tempTPwd = tempYPwd.toString(); } BigDecimal tempTPwdBD = new BigDecimal(tempTPwd); BigDecimal tempZPwdBD = tempTPwdBD.add(oldPwdBD); if (tempZPwdBD.intValue() < 1000000) { tempZPwdBD = tempZPwdBD.subtract(new BigDecimal("135791")); newPwd = tempZPwdBD.abs().toString(); } else { tempZPwdBD = tempZPwdBD.subtract(new BigDecimal("1000000")); tempZPwdBD = tempZPwdBD.subtract(new BigDecimal("135791")); newPwd = tempZPwdBD.abs().toString(); } // 如果netPwd最后获取的是0,则加密后的密码为999888 if (newPwd.equals("0")) { return "999888"; } else { StringBuilder tempNewPwd = new StringBuilder(); for (int x = 0; x < 6 - newPwd.length(); x++) { tempNewPwd.append("0"); } tempNewPwd.append(newPwd); return tempNewPwd.toString(); } }
static Map<Long, BigDecimal> extract( BigDecimal amountToExtract, Map<Long, BigDecimal> mapToExtractFrom) { BigDecimal weightCollected = BigDecimal.ZERO; Map<Long, BigDecimal> result = new HashMap<>(); BigDecimal availableWeightSum = mapToExtractFrom.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add); for (Map.Entry<Long, BigDecimal> entry : mapToExtractFrom.entrySet()) { long receiptItemId = entry.getKey(); BigDecimal weight = entry.getValue(); if (weightCollected.compareTo(amountToExtract) == 0 || availableWeightSum.compareTo(weightCollected) == 0) return result; // needed is LESS than receipt item available weight if (amountToExtract.compareTo(weight) < 0) { result.put(receiptItemId, amountToExtract); mapToExtractFrom.put(receiptItemId, weight.subtract(amountToExtract)); return result; } else { // When needed weight is same or bigger than offered - taking it all result.put(receiptItemId, weight); mapToExtractFrom.put(receiptItemId, BigDecimal.ZERO); amountToExtract = amountToExtract.subtract(weight); } } return result; }
public static BigDecimal calculateDiscount( BigDecimal basePrice, VoucherResponse voucher, BigDecimal unitPrice) { Discount discount = voucher.getDiscount(); if (discount.getType() == DiscountType.PERCENT) { validatePercentDiscount(discount); return basePrice .multiply(valueOf(discount.getPercentOff() / 100.0)) .setScale(2, RoundingMode.HALF_UP); } else if (discount.getType() == DiscountType.AMOUNT) { validateAmountDiscount(discount); BigDecimal amountOff = valueOf(discount.getAmountOff() / 100.0); BigDecimal newPrice = basePrice.subtract(amountOff).setScale(2, RoundingMode.HALF_UP); return (newPrice.doubleValue() > 0 ? amountOff : basePrice).setScale(2, RoundingMode.HALF_UP); } else if (discount.getType() == DiscountType.UNIT) { validateUnitDiscount(discount); BigDecimal amountOff = unitPrice.multiply(valueOf(discount.getUnitOff())); BigDecimal newPrice = basePrice.subtract(amountOff).setScale(2, RoundingMode.HALF_UP); return (newPrice.doubleValue() > 0 ? amountOff : basePrice).setScale(2, RoundingMode.HALF_UP); } else { throw new RuntimeException("Unknown voucher type"); } }
/** * determine the change in q if a node were to move to the given community. * * @param currCommunityId * @param testCommunityId * @param testSigmaTot * @param edgeWeightInCommunity (sum of weight of edges from this ndoe to target community) * @param nodeWeight (the node degree) * @param internalWeight * @return */ private BigDecimal q( String currCommunityId, String testCommunityId, long testSigmaTot, long edgeWeightInCommunity, long nodeWeight, long internalWeight) { boolean isCurrentCommunity = (currCommunityId.equals(testCommunityId)); BigDecimal M = new BigDecimal(Long.toString(getTotalEdgeWeight())); long k_i_in_L = (isCurrentCommunity) ? edgeWeightInCommunity + internalWeight : edgeWeightInCommunity; BigDecimal k_i_in = new BigDecimal(Long.toString(k_i_in_L)); BigDecimal k_i = new BigDecimal(Long.toString(nodeWeight + internalWeight)); BigDecimal sigma_tot = new BigDecimal(Long.toString(testSigmaTot)); if (isCurrentCommunity) { sigma_tot = sigma_tot.subtract(k_i); } // diouble sigma_tot_temp = (isCurrentCommunity) ? testSigmaTot - k_i : // testSigmaTot; BigDecimal deltaQ = new BigDecimal("0.0"); if (!(isCurrentCommunity && sigma_tot.equals(deltaQ))) { BigDecimal dividend = k_i.multiply(sigma_tot); int scale = 20; deltaQ = k_i_in.subtract(dividend.divide(M, scale, RoundingMode.HALF_DOWN)); } return deltaQ; }
protected void changeShapeSize( GraphicsType annType, NodeType node, BigDecimal newHeight, BigDecimal newWidth, Map<String, AnnotationData> annotations) { super.changeShapeSize(annType, node, newHeight, newWidth, annotations); BigDecimal oldH = annType.getSize().getHeight(); BigDecimal oldW = annType.getSize().getWidth(); BigDecimal oldX = annType.getPosition().get(0).getX(); BigDecimal oldY = annType.getPosition().get(0).getY(); BigDecimal newX = oldW.subtract(newWidth).divide(divisor).add(oldX); BigDecimal newY = oldH.subtract(newHeight).divide(divisor).add(oldY); SizeType size = new SizeType(); size.setHeight(newHeight); size.setWidth(newWidth); PositionType position = new PositionType(); position.setX(newX); position.setY(newY); annType.setSize(size); annType.getPosition().remove(0); annType.getPosition().add(position); annotations.put( node.getId(), new AnnotationData(oldX, oldY, newX, newY, oldH, oldW, newHeight, newWidth)); }
public static BigDecimal[] salaryCalculationProportionally( Employee[] section, BigDecimal fondSalary) { BigDecimal fondVariable = fondSalary; BigDecimal[] salaries = new BigDecimal[section.length]; BigDecimal sumOfSalary = new BigDecimal("0.00"); // переменная для поверки достаточности фонда для начисления зп boolean[] birthDayBonus = birthDayBonus(section); for (int i = 0; i < salaries.length; i++) { BigDecimal employeeSalary = section[i].getSalary(); salaries[i] = employeeSalary; sumOfSalary = sumOfSalary.add(employeeSalary); fondVariable = fondVariable.subtract(employeeSalary); if (section[i] instanceof Manager) { Manager manager = (Manager) section[i]; BigDecimal managerBonus = (BigDecimal.valueOf(manager.getSubordinateEmployees().size())) .multiply(new BigDecimal("20.00")); salaries[i].add(managerBonus); sumOfSalary = sumOfSalary.add(managerBonus); fondVariable = fondVariable.subtract(managerBonus); } // начисление бонусов за день рожденья if (birthDayBonus[i] == true) { salaries[i] = salaries[i].add(new BigDecimal(200.00)); fondVariable = fondVariable.subtract(new BigDecimal(200.00)); sumOfSalary = sumOfSalary.add(new BigDecimal(200.00)); fondVariable = fondVariable.subtract(new BigDecimal(200.00)); } } // проверка достаточности фонда для начисления зп if (sumOfSalary.doubleValue() > fondSalary.doubleValue()) { System.out.println("Salary fund is insufficient! Please, change the amount of salary fund!"); System.out.println("The amount should be at least " + sumOfSalary); } else { // вычиление коэффициента для начисления премии пропорционально BigDecimal[] factor = new BigDecimal[section.length]; for (int i = 0; i < section.length; i++) { factor[i] = section[i].getSalary().divide(sumOfSalary, 2, BigDecimal.ROUND_HALF_EVEN); } for (int i = 0; i < section.length; i++) { salaries[i] = salaries[i] .add(factor[i].multiply(fondVariable)) .setScale(2, BigDecimal.ROUND_HALF_EVEN); // System.out.println(section[i].getName() + " " + salaries[i].toString()); } } return salaries; }
/** * Set Line Net Amt Difference * * @param diff difference (to be subtracted) */ public void setLineNetAmtDifference(BigDecimal diff) { String msg = "Diff=" + diff + " - LineNetAmt=" + m_LineNetAmt; m_LineNetAmt = m_LineNetAmt.subtract(diff); m_DiscountAmt = m_ListAmt.subtract(m_LineNetAmt); setAmount(m_ListAmt, m_DiscountAmt); msg += " -> " + m_LineNetAmt; log.fine(msg); } // setLineNetAmtDifference
public void lose(BigDecimal amount, DateTime time) throws Exception { if (currentAmount.subtract(amount).compareTo(BigDecimal.ZERO) == -1) { throw new Exception("Account is overdrawn"); } currentAmount = currentAmount.subtract(amount); writeToEquityCurve(time); }
@Override public void Shift(float xDelta, float yDelta, Point2D Center) { X1 = X1.subtract(new BigDecimal(Float.toString(xDelta))); Y1 = Y1.subtract(new BigDecimal(Float.toString(yDelta))); X2 = X2.subtract(new BigDecimal(Float.toString(xDelta))); Y2 = Y2.subtract(new BigDecimal(Float.toString(yDelta))); Zoom(CurrentZoom, Center); }
public Amount<Q> minus(Amount<Q> other) { if (other.value.equals(BigDecimal.ZERO)) { return this; } int diff = units.compareTo(other.units); if (diff == 0) { return new Amount<Q>(value.subtract(other.value), units); } if (diff < 0) { return new Amount<Q>(value.subtract(other.units.scaleTo(other.value, units)), units); } return new Amount<Q>(units.scaleTo(value, other.units).subtract(other.value), other.units); }
public BigDecimal roundOffToNearestEven(final BigDecimal amount) { BigDecimal roundedAmt; final BigDecimal remainder = amount.remainder(new BigDecimal(2)); /* * if reminder is less than 1, subtract reminder amount from passed * amount else reminder is greater than 1, subtract reminder amount from * passed amount and add 5 to result amount */ if (remainder.compareTo(new BigDecimal("1")) == 1) roundedAmt = amount.subtract(remainder).add(new BigDecimal(2)); else roundedAmt = amount.subtract(remainder); return roundedAmt; }
public static BigDecimal[] salaryCalculationEvenly(Employee[] section, BigDecimal fondSalary) { BigDecimal fondVariable = fondSalary; BigDecimal[] salaryOfSection = new BigDecimal[section.length]; BigDecimal sumOfSalary = new BigDecimal("0.00"); boolean[] birthDayBonus = birthDayBonus(section); for (int i = 0; i < salaryOfSection.length; i++) { salaryOfSection[i] = section[i].getSalary(); sumOfSalary = sumOfSalary.add(section[i].getSalary()); fondVariable = fondVariable.subtract(section[i].getSalary()); if (section[i] instanceof Manager) { Manager manager = (Manager) section[i]; BigDecimal managerBonus = (BigDecimal.valueOf(manager.getSubordinateEmployees().size())) .multiply(new BigDecimal("20.00")); salaryOfSection[i].add(managerBonus); sumOfSalary = sumOfSalary.add(managerBonus); fondVariable = fondVariable.subtract(managerBonus); } if (birthDayBonus[i] == true) { salaryOfSection[i] = salaryOfSection[i].add(new BigDecimal("200.00")); fondVariable = fondVariable.subtract(new BigDecimal("200.00")); sumOfSalary = sumOfSalary.add(new BigDecimal(200.00)); fondVariable = fondVariable.subtract(new BigDecimal(200.00)); } } if (sumOfSalary.doubleValue() > fondSalary.doubleValue()) { System.out.println("Salary fund is insufficient! Please, change the amount of salary fund!"); System.out.println("The amount should be at least " + sumOfSalary); } else { BigDecimal bonus = fondVariable.divide( new BigDecimal(new Integer(section.length).toString()), 2, BigDecimal.ROUND_HALF_EVEN); for (int i = 0; i < salaryOfSection.length; i++) { salaryOfSection[i] = salaryOfSection[i].add(bonus); // System.out.println(section[i].getName() + " " + // salaryOfSection[i].toString()); } } return salaryOfSection; }
public static void main(String[] args) { BigDecimal f1 = new BigDecimal("0.05"); BigDecimal f2 = BigDecimal.valueOf(0.01); BigDecimal f3 = new BigDecimal(0.05); System.out.println("使用String作为BigDecimal构造器参数:"); System.out.println("0.05 + 0.01 = " + f1.add(f2)); System.out.println("0.05 - 0.01 = " + f1.subtract(f2)); System.out.println("0.05 * 0.01 = " + f1.multiply(f2)); System.out.println("0.05 / 0.01 = " + f1.divide(f2)); System.out.println("使用double作为BigDecimal构造器参数:"); System.out.println("0.05 + 0.01 = " + f3.add(f2)); System.out.println("0.05 - 0.01 = " + f3.subtract(f2)); System.out.println("0.05 * 0.01 = " + f3.multiply(f2)); System.out.println("0.05 / 0.01 = " + f3.divide(f2)); }
// Subtract given amount of money, returning a new amount of money public Money subtract(Money money) { // if (amount.compareTo(money.getAmount()) < 0){ // System.out.println("the amount withdraw is greater than the amount in the account!"); // return new Money(amount); // } return new Money(amount.subtract(money.getAmount())); }
public static BigDecimal get(final BigDecimal n) { // Make sure n is a positive number if (n.compareTo(ZERO) <= 0) { throw new IllegalArgumentException(); } final BigDecimal initialGuess = getInitialApproximation(n); BigDecimal lastGuess = ZERO; BigDecimal guess = new BigDecimal(initialGuess.toString()); // Iterate iterations = 0; boolean more = true; while (more) { lastGuess = guess; guess = n.divide(guess, scale, BigDecimal.ROUND_HALF_UP); guess = guess.add(lastGuess); guess = guess.divide(TWO, scale, BigDecimal.ROUND_HALF_UP); error = n.subtract(guess.multiply(guess)); if (++iterations >= maxIterations) { more = false; } else if (lastGuess.equals(guess)) { more = error.abs().compareTo(ONE) >= 0; } } return guess; }
public static void assertEquals( final String message, final BigDecimal expected, final BigDecimal actual, final BigDecimal delta) { if (expected == actual) { return; } if (expected.compareTo(actual) == 0) { return; } final BigDecimal deltaActual = expected.subtract(actual).abs(); if (deltaActual.compareTo(delta) <= 0) { return; } Assert.fail( (message == null ? "" : message) + "\nExpected=<" + expected + ">" + "\nActual=<" + actual + ">" + "\nDelta=<" + delta + ">"); }
@Test public void test() { Human buyer = new Human(); Human seller = new Human(); seller.createConsumable(); final BigDecimal totalMoney = Money.MoneySupply.getTotalMoney(); final BigDecimal buyerWorth = buyer.getMonetaryWorth(); final BigDecimal sellerWorth = seller.getMonetaryWorth(); final int numSellerConsumables = seller.getNumConsumables(); final int numBuyerConsumables = buyer.getNumConsumables(); IConsumable product = seller.getItemsForSale().get(0); final int consumableId = product.getId(); final BigDecimal price = product.getPrice(); TransactionTerms transactionTerms = new TransactionTerms(price.multiply(new BigDecimal(2)), consumableId); TransactionAgreement agreement = buyer.proposeTransaction(seller, transactionTerms); new Transaction(buyer, seller, agreement); final BigDecimal totalMoneyAfterTrans = Money.MoneySupply.getTotalMoney(); final BigDecimal buyerPostWorth = buyer.getMonetaryWorth(); final BigDecimal sellerPostWorth = seller.getMonetaryWorth(); Assert.assertEquals(totalMoney, totalMoneyAfterTrans); Assert.assertEquals(buyerWorth.subtract(price.multiply(new BigDecimal(2))), buyerPostWorth); Assert.assertEquals(sellerWorth.add(price.multiply(new BigDecimal(2))), sellerPostWorth); Assert.assertEquals(numSellerConsumables - 1, seller.getNumConsumables()); Assert.assertEquals(numBuyerConsumables + 1, buyer.getNumConsumables()); }
private static JsonValue decimalEval(JsonNumber v1, JsonNumber v2, int op) { BigDecimal n1 = v1.decimalValue(); BigDecimal n2 = v2.decimalValue(); BigDecimal n3; switch (op) { case PLUS: { n3 = n1.add(n2, MathContext.DECIMAL128); break; } case MINUS: { n3 = n1.subtract(n2, MathContext.DECIMAL128); break; } case MULTIPLY: { n3 = n1.multiply(n2, MathContext.DECIMAL128); break; } case DIVIDE: { try { n3 = n1.divide(n2, MathContext.DECIMAL128); } catch (ArithmeticException e) { // TODO: need +INF, -INF, and NaN return null; } break; } default: throw new RuntimeException("invalid op:" + op); } return new JsonDecimal(n3); }
public static void main(String[] args) { Scanner input = new Scanner(System.in); String line = input.nextLine(); line = line.trim(); String[] numbers = line.split("[\\+\\- ]+"); ArrayList<String> signs = new ArrayList<String>(); Pattern p = Pattern.compile("([\\-\\+])"); Matcher m = p.matcher(line); while (m.find()) { String token = m.group(1); signs.add(token); } BigDecimal sum = new BigDecimal(numbers[0]); for (int i = 0; i < signs.size(); i++) { if (signs.get(i).equals("+")) { BigDecimal num = new BigDecimal(numbers[i + 1]); sum = sum.add(num); } else { BigDecimal num = new BigDecimal(numbers[i + 1]); sum = sum.subtract(num); } } System.out.printf("%1$s", sum.toPlainString()); input.close(); }
/** * Create shipment/receipt line * * @param invoice * @param invoiceLine * @return shipment/receipt line */ private MInOutLine createLine(MInvoice invoice, MInvoiceLine invoiceLine) { BigDecimal qtyMatched = invoiceLine.getMatchedQty(); BigDecimal qtyInvoiced = invoiceLine.getQtyInvoiced(); BigDecimal qtyNotMatched = qtyInvoiced.subtract(qtyMatched); // If is fully matched don't create anything if (qtyNotMatched.signum() == 0) { return null; } MInOut inout = getCreateHeader(invoice); MInOutLine sLine = new MInOutLine(inout); sLine.setInvoiceLine( invoiceLine, 0, // Locator invoice.isSOTrx() ? qtyNotMatched : Env.ZERO); sLine.setQtyEntered(qtyNotMatched); sLine.setMovementQty(qtyNotMatched); if (invoice.isCreditMemo()) { sLine.setQtyEntered(sLine.getQtyEntered().negate()); sLine.setMovementQty(sLine.getMovementQty().negate()); } sLine.saveEx(); // invoiceLine.setM_InOutLine_ID(sLine.getM_InOutLine_ID()); invoiceLine.saveEx(); // return sLine; }
/** * Calculates Gain or Loss for the tax lot line and determines if it's long term or short term * * @param holdingTaxLot * @param taxLotLine * @param valueReceived * @param originalCost */ private void calculateGainLoss( HoldingTaxLot holdingTaxLot, EndowmentTransactionTaxLotLine taxLotLine, BigDecimal valueReceived, BigDecimal originalCost) { BigDecimal gainOrLoss = valueReceived.subtract(originalCost); gainOrLoss = gainOrLoss.setScale(2, BigDecimal.ROUND_HALF_UP); // Determine if short or long term gain/loss Date currentDate = kemService.getCurrentDate(); Date acquiredDate = holdingTaxLot.getAcquiredDate(); Calendar calendarAcquiredDate = Calendar.getInstance(); calendarAcquiredDate.setTime(acquiredDate); calendarAcquiredDate.add(Calendar.MONTH, EndowConstants.SHORT_VS_LONG_TERM_PERIOD); if (calendarAcquiredDate.getTime().before(currentDate)) { // long term gain/loss taxLotLine.setLotLongTermGainLoss(gainOrLoss); } // short term gain/loss else { taxLotLine.setLotShortTermGainLoss(gainOrLoss); } }
public BigDecimal previsao(BigDecimal total, String periodo) { BigDecimal diaUteis = BigDecimal.ONE; int diasUlteisTotal = diasUteis(true, periodo); int diasUlteisDecorridos = diasUteis(false, periodo); if (diasUlteisDecorridos < 2) { return BigDecimal.ZERO; } else { diaUteis = new BigDecimal(diasUlteisDecorridos); diaUteis = diaUteis.subtract(BigDecimal.ONE); } BigDecimal mediaDiaria; if (total != null) { mediaDiaria = total.divide( diaUteis.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ONE : diaUteis, 2, RoundingMode.HALF_UP); } else { mediaDiaria = BigDecimal.ZERO; } return mediaDiaria.multiply(new BigDecimal(diasUlteisTotal)); }