/** @return Returns the invoiceItemSubTotalAmount. */ public BigDecimal getInvoiceItemSubTotalAmount() { // this needs to be calculated when read BigDecimal returnValue; if (((this.invoiceItemQuantity != null) && ((BigDecimal.ZERO.compareTo(this.invoiceItemQuantity)) != 0)) && ((this.invoiceItemUnitPrice != null) && ((BigDecimal.ZERO.compareTo(this.invoiceItemUnitPrice)) != 0))) { // unit price and quantity are valid... calculate subtotal returnValue = this.invoiceItemQuantity.multiply(this.invoiceItemUnitPrice); } else if (((this.invoiceItemQuantity == null) || ("".equals(this.invoiceItemQuantity))) && ((this.invoiceItemUnitPrice != null) && ((BigDecimal.ZERO.compareTo(this.invoiceItemUnitPrice)) != 0))) { // quantity is empty but unit cost exists... use it returnValue = this.invoiceItemUnitPrice; } else { returnValue = null; } if (returnValue != null) { invoiceItemSubTotalAmount = returnValue.setScale(4, BigDecimal.ROUND_HALF_UP); } else { invoiceItemSubTotalAmount = null; } return invoiceItemSubTotalAmount; }
@Test public final void shouldValuesEqualsReturnCorrectValue() { Assert.assertTrue(BigDecimalUtils.valueEquals(null, null)); Assert.assertFalse(BigDecimalUtils.valueEquals(null, BigDecimal.ZERO)); Assert.assertFalse(BigDecimalUtils.valueEquals(BigDecimal.ZERO, null)); Assert.assertFalse(BigDecimalUtils.valueEquals(BigDecimal.ONE, BigDecimal.ZERO)); Assert.assertTrue( BigDecimalUtils.valueEquals(BigDecimal.ZERO.setScale(100), BigDecimal.ZERO.setScale(2))); }
/** * 数值求余处理 * * @param num1 被除数 * @param num2 除数 * @return 余数 */ public static BigDecimal remainder(BigDecimal num1, BigDecimal num2) { if (null == num2 || BigDecimal.ZERO.compareTo(num2) == 0) { return null; } if (null == num1 || BigDecimal.ZERO.compareTo(num1) == 0) { return BigDecimal.ZERO; } return num1.remainder(num2); }
public boolean process(PaymentDTOEx payment) throws PluggableTaskException { LOG.debug("Payment processing for " + getProcessorName() + " gateway"); if (payment.getPayoutId() != null) return true; SvcType transaction = SvcType.SALE; if (BigDecimal.ZERO.compareTo(payment.getAmount()) > 0 || (payment.getIsRefund() != 0)) { LOG.debug("Doing a refund using credit card transaction"); transaction = SvcType.REFUND_CREDIT; } boolean result; try { result = doProcess(payment, transaction, null).shouldCallOtherProcessors(); LOG.debug( "Processing result is " + payment.getPaymentResult().getId() + ", return value of process is " + result); } catch (Exception e) { LOG.error("Exception", e); throw new PluggableTaskException(e); } return result; }
@Override public ByteBuffer write(ByteBuffer buff, Object obj) { if (!isBigDecimal(obj)) { return super.write(buff, obj); } BigDecimal x = (BigDecimal) obj; if (BigDecimal.ZERO.equals(x)) { buff.put((byte) TAG_BIG_DECIMAL_0); } else if (BigDecimal.ONE.equals(x)) { buff.put((byte) TAG_BIG_DECIMAL_1); } else { int scale = x.scale(); BigInteger b = x.unscaledValue(); int bits = b.bitLength(); if (bits < 64) { if (scale == 0) { buff.put((byte) TAG_BIG_DECIMAL_SMALL); } else { buff.put((byte) TAG_BIG_DECIMAL_SMALL_SCALED); DataUtils.writeVarInt(buff, scale); } DataUtils.writeVarLong(buff, b.longValue()); } else { buff.put((byte) TYPE_BIG_DECIMAL); DataUtils.writeVarInt(buff, scale); byte[] bytes = b.toByteArray(); DataUtils.writeVarInt(buff, bytes.length); buff = DataUtils.ensureCapacity(buff, bytes.length); buff.put(bytes); } } return buff; }
private BigDecimal randomExpenseAmount(Account account, Date date, Double part) { BigDecimal balance = balanceWorker.getBalance(account.getId(), date); if (BigDecimal.ZERO.compareTo(balance) >= 0) return BigDecimal.ZERO; else { return new BigDecimal((int) (Math.random() * balance.doubleValue() * part)); } }
@Test @WithMockUser(roles = "Tutor") public void noAppointmentBill() throws Exception { mockMvc .perform(get("/bill").principal(this.authUser)) .andExpect(model().attribute("balance", BigDecimal.ZERO.setScale(2))); }
public class BillSubtotalUpdate extends Update { private BigDecimal amount = BigDecimal.ZERO.setScale(2); public BillSubtotalUpdate(BigDecimal amount) { this.amount = amount; } @Override public boolean equals(Object other) { // check for self-comparison if (this == other) return true; // use instanceof instead of getClass here for two reasons // 1. if need be, it can match any supertype, and not just one class; // 2. it renders an explict check for "that == null" redundant, since // it does the check for null already - "null instanceof [type]" always // returns false. (See Effective Java by Joshua Bloch.) if (!(other instanceof BillSubtotalUpdate)) return false; // cast to native object is now safe BillSubtotalUpdate otherBSA = (BillSubtotalUpdate) other; // now a proper field-by-field evaluation can be made return EqualsUtil.areEqual(this.amount, otherBSA.amount); } public BigDecimal getAmount() { return this.amount; } public String toString() { return "BillSubtotal(" + this.amount + ")"; } }
private static BigDecimal defaultToNullIfZero(final BigDecimal value) { BigDecimal result = value; if (value != null && BigDecimal.ZERO.compareTo(value) == 0) { result = null; } return result; }
private void transfer(final Date date, final Account account1, final Account account2) { persistence.runInTransaction( em -> { BigDecimal amount1 = randomExpenseAmount(account1, date, 0.5); if (BigDecimal.ZERO.compareTo(amount1) >= 0) return; BigDecimal amount2 = transferAmount(account1, account2, amount1); Operation operation = metadata.create(Operation.class); operation.setOpType(OperationType.TRANSFER); operation.setOpDate(date); operation.setAcc1(account1); operation.setAmount1(amount1); operation.setAcc2(account2); operation.setAmount2(amount2); em.persist(operation); log.info( "Transfer: " + date + ", " + account1.getName() + ", " + amount1 + ", " + account2.getName() + ", " + amount2); }); }
@Override public void write(WriteBuffer buff, Object obj) { if (!isBigDecimal(obj)) { super.write(buff, obj); return; } BigDecimal x = (BigDecimal) obj; if (BigDecimal.ZERO.equals(x)) { buff.put((byte) TAG_BIG_DECIMAL_0); } else if (BigDecimal.ONE.equals(x)) { buff.put((byte) TAG_BIG_DECIMAL_1); } else { int scale = x.scale(); BigInteger b = x.unscaledValue(); int bits = b.bitLength(); if (bits < 64) { if (scale == 0) { buff.put((byte) TAG_BIG_DECIMAL_SMALL); } else { buff.put((byte) TAG_BIG_DECIMAL_SMALL_SCALED).putVarInt(scale); } buff.putVarLong(b.longValue()); } else { byte[] bytes = b.toByteArray(); buff.put((byte) TYPE_BIG_DECIMAL).putVarInt(scale).putVarInt(bytes.length).put(bytes); } } }
public void deposit(BigDecimal amount) { if (BigDecimal.ZERO.compareTo(amount) == 0) { throw new IllegalArgumentException("Amount must be greater than zero/"); } transactions.add(new Transaction(amount, Transaction.Type.DEPOSIT)); }
public Product(String name, BigDecimal price, String description) { Assert.hasText(name, "Name must not be null or empty!"); Assert.isTrue(BigDecimal.ZERO.compareTo(price) < 0, "Price must be greater than zero!"); this.name = name; this.price = price; this.description = description; }
public static List<OrderLineDTO> diffOrderLines( List<OrderLineDTO> lines1, List<OrderLineDTO> lines2) { List<OrderLineDTO> diffLines = new ArrayList<OrderLineDTO>(); Collections.sort( lines1, new Comparator<OrderLineDTO>() { public int compare(OrderLineDTO a, OrderLineDTO b) { return new Integer(a.getId()).compareTo(b.getId()); } }); for (OrderLineDTO line : lines2) { int index = Collections.binarySearch( lines1, line, new Comparator<OrderLineDTO>() { public int compare(OrderLineDTO a, OrderLineDTO b) { return new Integer(a.getId()).compareTo(b.getId()); } }); if (index >= 0) { // existing line OrderLineDTO diffLine = new OrderLineDTO(lines1.get(index)); // will fail if amounts or quantities are null... diffLine.setAmount(line.getAmount().subtract(diffLine.getAmount())); diffLine.setQuantity(line.getQuantity().subtract(diffLine.getQuantity())); if (BigDecimal.ZERO.compareTo(diffLine.getAmount()) != 0 || BigDecimal.ZERO.compareTo(diffLine.getQuantity()) != 0) { diffLines.add(diffLine); } } else { // new line diffLines.add(new OrderLineDTO(line)); } } LOG.debug("Diff lines are %s", diffLines); return diffLines; }
@Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append('('); sb.append(DEFAULT_FORMAT.format(re)); if (!BigDecimal.ZERO.equals(im)) sb.append(',').append(DEFAULT_FORMAT.format(im)).append('i'); sb.append(')'); return sb.toString(); }
/** * Creates a new {@link Product} from the given name and description. * * @param id a unique Id * @param name must not be {@literal null} or empty. * @param price must not be {@literal null} or less than or equal to zero. * @param description */ @PersistenceConstructor public Product(Long id, String name, BigDecimal price, String description) { super(id); Assert.hasText(name, "Name must not be null or empty!"); Assert.isTrue(BigDecimal.ZERO.compareTo(price) < 0, "Price must be greater than zero!"); this.name = name; this.price = price; this.description = description; }
public void process(Event event) throws PluggableTaskException { if (event instanceof SubscriptionActiveEvent) { SubscriptionActiveEvent activeEvent = (SubscriptionActiveEvent) event; LOG.debug("Processing order " + activeEvent.getOrder().getId() + " subscription activation"); doActivate(activeEvent.getOrder(), activeEvent.getOrder().getLines()); } else if (event instanceof SubscriptionInactiveEvent) { SubscriptionInactiveEvent inactiveEvent = (SubscriptionInactiveEvent) event; LOG.debug( "Processing order " + inactiveEvent.getOrder().getId() + " subscription deactivation"); doDeactivate(inactiveEvent.getOrder(), inactiveEvent.getOrder().getLines()); } else if (event instanceof NewQuantityEvent) { NewQuantityEvent quantityEvent = (NewQuantityEvent) event; if (BigDecimal.ZERO.compareTo(quantityEvent.getOldQuantity()) != 0 && BigDecimal.ZERO.compareTo(quantityEvent.getNewQuantity()) != 0) { LOG.debug("Order line quantities did not change, no provisioning necessary."); return; } OrderDTO order = new OrderBL(quantityEvent.getOrderId()).getEntity(); if (!isOrderProvisionable(order)) { LOG.warn("Order is not active and cannot be provisioned."); return; } if (BigDecimal.ZERO.compareTo(quantityEvent.getOldQuantity()) == 0) { LOG.debug("Processing order " + order.getId() + " activation"); doActivate(order, Arrays.asList(quantityEvent.getOrderLine())); } if (BigDecimal.ZERO.compareTo(quantityEvent.getNewQuantity()) == 0) { LOG.debug("Processing order " + order.getId() + " deactivation"); doDeactivate(order, Arrays.asList(quantityEvent.getOrderLine())); } } else { throw new PluggableTaskException("Cannot process event " + event); } }
public void withdraw(BigDecimal amount) { if (BigDecimal.ZERO.compareTo(amount) == 0) { throw new IllegalArgumentException("Amount must be greater than zero."); } if (sumTransactions().compareTo(amount) < 0) { throw new IllegalArgumentException("Customer doesn't have enough money to cover withdrawal"); } // TBD watch the sign direction on these transactions.add(new Transaction(amount.negate(), Transaction.Type.WITHDRAWAL)); }
public BigDecimal getBudgetIncomeAmount() { if (isBudgetIncome() && (budgetIncomeAmount == null || BigDecimal.ZERO.setScale(2).equals(budgetIncomeAmount.setScale(2)))) { return getAmount(); } if (!isBudgetIncome()) { return BigDecimal.ZERO; } return budgetIncomeAmount; }
@Transient public BigDecimal getValue(Date currentStartDate, Date currentEndDate, Currency targetCurrency) { BigDecimal valueForDate = BigDecimal.ZERO.setScale(4); for (PortfolioShare portfolioShare : this.getListShares().values()) { BigDecimal psValueForDate = portfolioShare.getValue(currentStartDate, currentEndDate, targetCurrency); valueForDate = valueForDate.add(psValueForDate); } return valueForDate; }
public BigDecimal getTotalFee() { BigDecimal fee = BigDecimal.ZERO.setScale(8); for (Transaction transaction : this.getTransactions()) { fee = fee.add(transaction.getFee()); } fee = fee.add(BigDecimal.valueOf(this.atFees, 8)); return fee; }
public BigDecimal costoUnitarioCargoLegajo() { int meshoras = 0; try { meshoras = this.ContarHorasDedicacionCargoLegajo() * 4; if (meshoras > 0) { return this.ContarSueldoBasicoCargoLegajo() .divide(BigDecimal.valueOf(Double.valueOf("" + meshoras)), RoundingMode.HALF_UP) .setScale(2); } else { return BigDecimal.ZERO.setScale(2, RoundingMode.CEILING); } } catch (Exception ex) { System.out.println( "No se realizo la consulta en la extraccion de costo unitario por cargos " + ex); return BigDecimal.ZERO.setScale(2); } }
protected JSONObject execute(Map<String, Object> parameters, String data) { final DataToJsonConverter jsonConverter = new DataToJsonConverter(); JSONObject json = null; try { String orderId = (String) parameters.get("orderId"); Order objOrder = OBDal.getInstance().get(Order.class, orderId); Order objCloneOrder = (Order) DalUtil.copy(objOrder, false); BigDecimal bLineNetAmt = getLineNetAmt(orderId); objCloneOrder.setDocumentAction("CO"); objCloneOrder.setDocumentStatus("DR"); objCloneOrder.setPosted("N"); objCloneOrder.setProcessed(false); objCloneOrder.setSalesTransaction(true); objCloneOrder.setDocumentNo(null); objCloneOrder.setSalesTransaction(objOrder.isSalesTransaction()); // save the cloned order object OBDal.getInstance().save(objCloneOrder); objCloneOrder.setSummedLineAmount(objCloneOrder.getSummedLineAmount().subtract(bLineNetAmt)); objCloneOrder.setGrandTotalAmount(objCloneOrder.getGrandTotalAmount().subtract(bLineNetAmt)); // get the lines associated with the order and clone them to the new // order line. for (OrderLine ordLine : objOrder.getOrderLineList()) { String strPriceVersionId = getPriceListVersion(objOrder.getPriceList().getId(), objOrder.getClient().getId()); BigDecimal bdPriceList = getPriceList(ordLine.getProduct().getId(), strPriceVersionId); OrderLine objCloneOrdLine = (OrderLine) DalUtil.copy(ordLine, false); objCloneOrdLine.setReservedQuantity(new BigDecimal("0")); objCloneOrdLine.setDeliveredQuantity(new BigDecimal("0")); objCloneOrdLine.setInvoicedQuantity(new BigDecimal("0")); if (!"".equals(bdPriceList) || bdPriceList != null || !bdPriceList.equals(BigDecimal.ZERO.setScale(bdPriceList.scale()))) { objCloneOrdLine.setListPrice(bdPriceList); } objCloneOrder.getOrderLineList().add(objCloneOrdLine); objCloneOrdLine.setSalesOrder(objCloneOrder); } OBDal.getInstance().save(objCloneOrder); OBDal.getInstance().flush(); OBDal.getInstance().refresh(objCloneOrder); json = jsonConverter.toJsonObject(objCloneOrder, DataResolvingMode.FULL); OBDal.getInstance().commitAndClose(); return json; } catch (Exception e) { throw new OBException(e); } }
@org.junit.Test public void testBorderValue2Equality() throws IOException { final java.util.List<java.math.BigDecimal> borderValue2 = new java.util.ArrayList<java.math.BigDecimal>( java.util.Arrays.asList(java.math.BigDecimal.ZERO.setScale(2))); final StaticJson.Bytes borderValue2JsonSerialized = jsonSerialization.serialize(borderValue2); final java.util.List<java.math.BigDecimal> borderValue2JsonDeserialized = jsonSerialization.deserializeList( java.math.BigDecimal.class, borderValue2JsonSerialized.content, borderValue2JsonSerialized.length); MoneyAsserts.assertNullableListOfNullableEquals(borderValue2, borderValue2JsonDeserialized); }
@Test public final void shouldConvertNullToZero() { // given BigDecimal notNullDecimal = BigDecimal.TEN; // when BigDecimal fromNullRes = BigDecimalUtils.convertNullToZero(null); BigDecimal fromNotNullRes = BigDecimalUtils.convertNullToZero(notNullDecimal); // then Assert.assertEquals(0, notNullDecimal.compareTo(fromNotNullRes)); Assert.assertEquals(0, BigDecimal.ZERO.compareTo(fromNullRes)); }
public void testNegativeZero(int scale, IonDecimal actual) { assertEquals(-0f, actual.floatValue()); assertEquals(-0d, actual.doubleValue()); BigDecimal bd = actual.bigDecimalValue(); Decimal dec = actual.decimalValue(); assertEquals(0, BigDecimal.ZERO.compareTo(bd)); checkDecimal(0, scale, bd); checkDecimal(0, scale, dec); assertEquals(0, Decimal.NEGATIVE_ZERO.compareTo(dec)); assertTrue(dec.isNegativeZero()); }
private IcScriptUploadTradeRequestEntity packUp( CupsTrmnl cupsTrmnl, CupsKeyManage cupsKeyManage, PepsiColaRequestInfo request) throws TransferFailedException { if (request.getIcScript() == null) { throw new TransferFailedException( AppExCode.ILLEGAL_PARAMS, "isScript upload failed! IcScript objet is null"); } PayCups originalPayCups = payCupsService.findPayCups(request.getOriginalPayNo()); // 脚本上送打包 IcScriptUploadTradeRequestEntity entity = new IcScriptUploadTradeRequestEntity(); entity.setCardNo(originalPayCups.getCardNo()); // 2 卡号 entity.setProcessCode(originalPayCups.getProcessCode()); // 3 未选卡种 String amount = null; if (originalPayCups.getTransAmt() != null || BigDecimal.ZERO.compareTo(originalPayCups.getTransAmt()) != 0) { amount = com.newland.base.util.StringUtils.amtToBCD(originalPayCups.getTransAmt()); } entity.setTransAmt(amount); // 4 交易金额 entity.setTrmnlFlowNo(cupsTrmnl.getTrmnlFlowNo()); // 11 终端流水号 entity.setPosEntryMode(originalPayCups.getPosEntryMode()); // 22 卡输入方式 if (StringUtils.isBlank(originalPayCups.getIcData())) { // 磁条卡 entity.setSelfDefined60( Const.SD60_1_MSGTYPE_CONTROL + cupsTrmnl.getTrmnlBatchNo()); // 60 自定义域 22(交易类型码)+000001(批次号)+000(网络管理信息码) } else { // IC卡 entity.setCardSeqNum(originalPayCups.getCardSeqNum()); // IC卡必须上送该域 byte[] icData = getIcData(originalPayCups.getIcData(), request.getIcScript()); entity.setIcData(icData); // 55 IC卡数据 String selfDefined60 = Const.SD60_1_MSGTYPE_CONTROL + cupsTrmnl.getTrmnlBatchNo() + Const.SD60_3_IC_CRIPT_UPLOAD + Const.SD60_4_TERMINAL_READING_ABILITY_CONTACT_ICCARD + Const.SD60_5_IC_SERVICE_CODE_NORMAL; entity.setSelfDefined60(selfDefined60); } entity.setTrmnlRefferNo(originalPayCups.getTrmnlReferNo()); // 37 entity.setTrmnlNo(originalPayCups.getTrmnlNo()); // 41 终端号 entity.setTrmnlMrchNo(originalPayCups.getTrmnlMrchNo()); // 42 终端商户号 entity.setCurrency(originalPayCups.getCurrency()); // 49 货币代码 entity.setOriginalMessage( originalPayCups.getTrmnlBatchNo() + originalPayCups.getTrmnlFlowNo() + originalPayCups.getTransDate()); // 61 原批次号+原流水号 entity.setMacCode(new byte[8]); // 64 mac return entity; }
private double[] getFunctionalAsArray(Functional f) { int varCount = linearModel.getOrderedVariables().size(); double[] coefs = new double[varCount]; for (int i = 0; i < varCount; i++) { Variable v = linearModel.getOrderedVariables().get(i); BigDecimal term = f.getTermFor(v); double coef; if (term != null) { coef = term.doubleValue(); } else { coef = BigDecimal.ZERO.doubleValue(); } coefs[i] = coef; } return coefs; }
@Test public void anAsyncTransferIsTriggeredWhenWeTransferFromThePlayersAccount() throws GameException, WalletServiceException { underTest.forPlayer(GAME_PLAYER).decreaseBalanceBy(AMOUNT, AUDIT_LABEL, REFERENCE); verify(gameHostWallet) .post( TABLE_ID, GAME_ID, playerInfo, BigDecimal.ZERO.subtract(AMOUNT), TransactionType.Stake, AUDIT_LABEL, REFERENCE, NEW_UUID); }
public BigDecimal getAvgAmount() { if (StringUtil.isBlank(this.startTime) || StringUtil.isBlank(this.endTime) || BigDecimal.ZERO.equals(this.getAmount())) { return BigDecimal.ZERO; } if (this.timeUnit == TimeUnit.day) { return this.getAmount() .divide( BigDecimal.valueOf( DateUtil.interval( DateUtil.parse(this.endTime, "yyyyMMdd"), DateUtil.parse(this.startTime, "yyyyMMdd"), Calendar.DATE)), RoundingMode.HALF_DOWN); } return BigDecimal.ZERO; }