List of usage examples for java.math BigDecimal negate
public BigDecimal negate()
From source file:org.efaps.esjp.accounting.transaction.evaluation.DocumentInfo_Base.java
/** * Apply exchange gain loss./*from w ww . j a v a2 s. c o m*/ * * @param _parameter Parameter as passed by the eFaps API * @throws EFapsException on error */ public void applyExchangeGainLoss(final Parameter _parameter) throws EFapsException { final AccountInfo gainAcc = AccountInfo.get4Config(_parameter, AccountingSettings.PERIOD_EXCHANGEGAIN); final AccountInfo lossAcc = AccountInfo.get4Config(_parameter, AccountingSettings.PERIOD_EXCHANGELOSS); if (gainAcc != null && lossAcc != null) { final QueryBuilder queryBldr = new QueryBuilder(CISales.Payment); queryBldr.addWhereAttrEqValue(CISales.Payment.TargetDocument, getInstance()); final MultiPrintQuery multi = queryBldr.getPrint(); final SelectBuilder selDocInst = new SelectBuilder().linkto(CISales.Payment.FromAbstractLink) .instance(); final SelectBuilder selCurInst = new SelectBuilder().linkto(CISales.Payment.CurrencyLink).instance(); multi.addSelect(selDocInst, selCurInst); multi.addAttribute(CISales.Payment.Amount, CISales.Payment.Date); multi.execute(); while (multi.next()) { final Instance docInst = multi.getSelect(selDocInst); final PrintQuery print = new PrintQuery(docInst); final SelectBuilder selDocCurInst = new SelectBuilder() .linkto(CISales.DocumentSumAbstract.RateCurrencyId).instance(); print.addSelect(selDocCurInst); print.addAttribute(CIERP.DocumentAbstract.Date); print.execute(); final Instance curInst = multi.getSelect(selCurInst); final Instance docCurInst = print.getSelect(selDocCurInst); final DateTime docDate = print.getAttribute(CIERP.DocumentAbstract.Date); final DateTime dateTmp = multi.getAttribute(CISales.Payment.Date); final BigDecimal amountTmp = multi.getAttribute(CISales.Payment.Amount); if (!curInst.equals(Currency.getBaseCurrency()) || !docCurInst.equals(Currency.getBaseCurrency())) { final Currency currency = new Currency(); final RateInfo[] rateInfos1 = currency.evaluateRateInfos(_parameter, dateTmp, curInst, docCurInst); final RateInfo[] rateInfos2 = currency.evaluateRateInfos(_parameter, docDate, curInst, docCurInst); final int idx; // payment in BaseCurreny ==> Document was not BaseCurrency therefore current against target if (curInst.equals(Currency.getBaseCurrency())) { idx = 2; // Document in BaseCurrency ==> payment was not BaseCurrency therefore current against base } else if (docCurInst.equals(Currency.getBaseCurrency())) { idx = 0; // neither Document nor payment are BaseCurrency but are the same } else if (curInst.equals(docCurInst)) { idx = 0; } else { idx = 0; } final BigDecimal rate1 = RateInfo.getRate(_parameter, rateInfos1[idx], docInst.getType().getName()); final BigDecimal rate2 = RateInfo.getRate(_parameter, rateInfos2[idx], docInst.getType().getName()); if (rate1.compareTo(rate2) != 0) { final BigDecimal amount1 = amountTmp.divide(rate1, BigDecimal.ROUND_HALF_UP); final BigDecimal amount2 = amountTmp.divide(rate2, BigDecimal.ROUND_HALF_UP); BigDecimal gainLoss = amount1.subtract(amount2); if (idx == 2) { gainLoss = gainLoss.multiply(rate1); } if (gainLoss.compareTo(BigDecimal.ZERO) != 0) { final boolean out = getInstance().getType() .isKindOf(CISales.PaymentDocumentOutAbstract); if (out) { final boolean gain = gainLoss.compareTo(BigDecimal.ZERO) > 0; for (final AccountInfo accinfo : getCreditAccounts()) { if (accinfo.getDocLink() != null && accinfo.getDocLink().equals(docInst)) { final BigDecimal accAmount; if (accinfo.getRateInfo().getCurrencyInstance() .equals(Currency.getBaseCurrency())) { accAmount = gainLoss; } else { accAmount = gainLoss.multiply(accinfo.getRate(_parameter)); } accinfo.addAmount(accAmount.negate()); } } if (gain) { gainAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(), getInstance().getType().getName()); addCredit(gainAcc); } else { lossAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(), getInstance().getType().getName()); addDebit(lossAcc); } } else { final boolean gain = gainLoss.compareTo(BigDecimal.ZERO) < 0; for (final AccountInfo accinfo : getDebitAccounts()) { if (accinfo.getDocLink() != null && accinfo.getDocLink().equals(docInst)) { final BigDecimal accAmount; if (!accinfo.getRateInfo().getCurrencyInstance() .equals(Currency.getBaseCurrency())) { accAmount = gainLoss; } else { accAmount = gainLoss.multiply(accinfo.getRate(_parameter)); } accinfo.addAmount(accAmount); } } if (gain) { gainAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(), getInstance().getType().getName()); addDebit(gainAcc); } else { lossAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(), getInstance().getType().getName()); addCredit(lossAcc); } } } } } } } }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The inverse trigonometric sine.//from w w w . ja v a2s . c om * * @param x the argument. * @return the arcsin(x) in radians. */ static public BigDecimal asin(final BigDecimal x) { if (x.compareTo(BigDecimal.ONE) > 0 || x.compareTo(BigDecimal.ONE.negate()) < 0) { throw new ArithmeticException("Out of range argument " + x.toString() + " of asin"); } else if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ZERO; } else if (x.compareTo(BigDecimal.ONE) == 0) { /* arcsin(1) = pi/2 */ double errpi = Math.sqrt(x.ulp().doubleValue()); MathContext mc = new MathContext(err2prec(3.14159, errpi)); return pi(mc).divide(new BigDecimal(2)); } else if (x.compareTo(BigDecimal.ZERO) < 0) { return asin(x.negate()).negate(); } else if (x.doubleValue() > 0.7) { final BigDecimal xCompl = BigDecimal.ONE.subtract(x); final double xDbl = x.doubleValue(); final double xUlpDbl = x.ulp().doubleValue() / 2.; final double eps = xUlpDbl / 2. / Math.sqrt(1. - Math.pow(xDbl, 2.)); final BigDecimal xhighpr = scalePrec(xCompl, 3); final BigDecimal xhighprV = divideRound(xhighpr, 4); BigDecimal resul = BigDecimal.ONE; /* x^(2i+1) */ BigDecimal xpowi = BigDecimal.ONE; /* i factorial */ BigInteger ifacN = BigInteger.ONE; BigInteger ifacD = BigInteger.ONE; for (int i = 1;; i++) { ifacN = ifacN.multiply(new BigInteger("" + (2 * i - 1))); ifacD = ifacD.multiply(new BigInteger("" + i)); if (i == 1) { xpowi = xhighprV; } else { xpowi = multiplyRound(xpowi, xhighprV); } BigDecimal c = divideRound(multiplyRound(xpowi, ifacN), ifacD.multiply(new BigInteger("" + (2 * i + 1)))); resul = resul.add(c); /* series started 1+x/12+... which yields an estimate of the sums error */ if (Math.abs(c.doubleValue()) < xUlpDbl / 120.) { break; } } /* sqrt(2*z)*(1+...) */ xpowi = sqrt(xhighpr.multiply(new BigDecimal(2))); resul = multiplyRound(xpowi, resul); MathContext mc = new MathContext(resul.precision()); BigDecimal pihalf = pi(mc).divide(new BigDecimal(2)); mc = new MathContext(err2prec(resul.doubleValue(), eps)); return pihalf.subtract(resul, mc); } else { /* absolute error in the result is err(x)/sqrt(1-x^2) to lowest order */ final double xDbl = x.doubleValue(); final double xUlpDbl = x.ulp().doubleValue() / 2.; final double eps = xUlpDbl / 2. / Math.sqrt(1. - Math.pow(xDbl, 2.)); final BigDecimal xhighpr = scalePrec(x, 2); final BigDecimal xhighprSq = multiplyRound(xhighpr, xhighpr); BigDecimal resul = xhighpr.plus(); /* x^(2i+1) */ BigDecimal xpowi = xhighpr; /* i factorial */ BigInteger ifacN = BigInteger.ONE; BigInteger ifacD = BigInteger.ONE; for (int i = 1;; i++) { ifacN = ifacN.multiply(new BigInteger("" + (2 * i - 1))); ifacD = ifacD.multiply(new BigInteger("" + (2 * i))); xpowi = multiplyRound(xpowi, xhighprSq); BigDecimal c = divideRound(multiplyRound(xpowi, ifacN), ifacD.multiply(new BigInteger("" + (2 * i + 1)))); resul = resul.add(c); if (Math.abs(c.doubleValue()) < 0.1 * eps) { break; } } MathContext mc = new MathContext(err2prec(resul.doubleValue(), eps)); return resul.round(mc); } }
From source file:net.pms.util.Rational.java
/** * Returns an instance with the given {@code numerator} and * {@code denominator}.//from w ww . jav a2s .c om * * @param numerator the numerator. * @param denominator the denominator. * @return An instance that represents the value of {@code numerator}/ * {@code denominator}. */ @Nullable public static Rational valueOf(@Nullable BigDecimal numerator, @Nullable BigDecimal denominator) { if (numerator == null || denominator == null) { return null; } if (numerator.signum() == 0 && denominator.signum() == 0) { return NaN; } if (denominator.signum() == 0) { return numerator.signum() > 0 ? POSITIVE_INFINITY : NEGATIVE_INFINITY; } if (numerator.signum() == 0) { return ZERO; } if (numerator.equals(denominator)) { return ONE; } if (denominator.signum() < 0) { numerator = numerator.negate(); denominator = denominator.negate(); } int scale = Math.max(numerator.scale(), denominator.scale()); if (scale > 0) { numerator = numerator.scaleByPowerOfTen(scale); denominator = denominator.scaleByPowerOfTen(scale); } BigInteger biNumerator = numerator.toBigIntegerExact(); BigInteger biDenominator = denominator.toBigIntegerExact(); BigInteger reducedNumerator; BigInteger reducedDenominator; BigInteger greatestCommonDivisor = calculateGreatestCommonDivisor(biNumerator, biDenominator); if (BigInteger.ONE.equals(greatestCommonDivisor)) { reducedNumerator = biNumerator; reducedDenominator = biDenominator; } else { reducedNumerator = biNumerator.divide(greatestCommonDivisor); reducedDenominator = biDenominator.divide(greatestCommonDivisor); } return new Rational(biNumerator, biDenominator, greatestCommonDivisor, reducedNumerator, reducedDenominator); }
From source file:com.healthmarketscience.jackcess.impl.ColumnImpl.java
/** * Writes a numeric value./* w w w . j a va 2s. com*/ */ private void writeNumericValue(ByteBuffer buffer, Object value) throws IOException { Object inValue = value; try { BigDecimal decVal = toBigDecimal(value); inValue = decVal; int signum = decVal.signum(); if (signum < 0) { decVal = decVal.negate(); } // write sign byte buffer.put((signum < 0) ? NUMERIC_NEGATIVE_BYTE : 0); // adjust scale according to this column type (will cause the an // ArithmeticException if number has too many decimal places) decVal = decVal.setScale(getScale()); // check precision if (decVal.precision() > getPrecision()) { throw new IOException( "Numeric value is too big for specified precision " + getPrecision() + ": " + decVal); } // convert to unscaled BigInteger, big-endian bytes byte[] intValBytes = toUnscaledByteArray(decVal, getType().getFixedSize() - 1); if (buffer.order() != ByteOrder.BIG_ENDIAN) { fixNumericByteOrder(intValBytes); } buffer.put(intValBytes); } catch (ArithmeticException e) { throw (IOException) new IOException("Numeric value '" + inValue + "' out of range").initCause(e); } }
From source file:nl.strohalm.cyclos.services.accounts.AccountStatusHandlerImpl.java
/** * adds or substracts an amount to the status balance. Call this in stead of directly increasing credits or debits, as it takes care for rate * balance correction field too. Only updates the real credits and debits, not the pending debits and credits. * /*from w w w . ja va2 s . co m*/ * @param status The status to be updated. Nothing is saved; the status fields are just updated. * @param transfer the transfer being processed. */ private void updateBalanceWithTransfer(final PendingAccountStatus pendingStatus, final AccountStatus status, final Transfer transfer) { if (pendingStatus.getTransferStatus() != Payment.Status.PROCESSED) { // method only deals with real debits and credits; not with pendings... return; } final BigDecimal amount = transfer.getAmount(); final boolean isDebit = status.getAccount().equals(transfer.getFrom()); final boolean isRoot = transfer.isRoot(); final Currency currency = status.getAccount().getType().getCurrency(); final Calendar date = transfer.getProcessDate(); final boolean rated = (currency.isEnableARate(date) || currency.isEnableDRate(date)); if (isDebit) { // call this first, before the balance is updated. if (rated) { aRateService.updateRateBalanceCorrectionOnFromAccount(status, amount); } if (isRoot) { status.setRootDebits(status.getRootDebits().add(amount)); } else { status.setNestedDebits(status.getNestedDebits().add(amount)); } } else { // call this first, before the balance is updated. if (rated && amount.compareTo(BigDecimal.ZERO) < 0) { // special case for chargebacks (having negative transfer amounts) aRateService.updateRateBalanceCorrectionOnFromAccount(status, amount.negate()); } if (isRoot) { status.setRootCredits(status.getRootCredits().add(amount)); } else { status.setNestedCredits(status.getNestedCredits().add(amount)); } } }
From source file:org.efaps.esjp.accounting.transaction.Create_Base.java
/** * Analyse positions from ui.// ww w .jav a2 s . c om * * @param _parameter Parameter as passed by the eFaps API * @param _transInfo the trans info * @param _postFix the post fix * @param _accountOids the account oids * @param _executeRels the execute rels * @throws EFapsException on error */ public void analysePositionsFromUI(final Parameter _parameter, final TransInfo _transInfo, final String _postFix, final String[] _accountOids, final boolean _executeRels) throws EFapsException { @SuppressWarnings("unchecked") final Map<String, String> oidMap = (Map<String, String>) _parameter.get(ParameterValues.OIDMAP4UI); final String[] rowKeys = InterfaceUtils.getRowKeys(_parameter, "amount_" + _postFix, "amount_Debit", "amount_Credit"); final String[] accountOids = _accountOids == null ? _parameter.getParameterValues("accountLink_" + _postFix) : _accountOids; final String[] amounts = _parameter.getParameterValues("amount_" + _postFix); final String[] types = _parameter.getParameterValues("type_" + _postFix); final String[] rateCurIds = _parameter.getParameterValues("rateCurrencyLink_" + _postFix); final String[] acc2accOids = _parameter.getParameterValues("acc2acc_" + _postFix); final String[] labelLinkOids = _parameter.getParameterValues("labelLink_" + _postFix); final String[] docLinkOids = _parameter.getParameterValues("docLink_" + _postFix); final String[] remarks = _parameter.getParameterValues("remark_" + _postFix); final DecimalFormat formater = NumberFormatter.get().getFormatter(); try { Instance inst = _parameter.getCallInstance(); if (!inst.getType().isKindOf(CIAccounting.Period.getType())) { inst = new Period().evaluateCurrentPeriod(_parameter); } final Instance curInstance = new Period().getCurrency(inst).getInstance(); if (amounts != null) { for (int i = 0; i < amounts.length; i++) { final Instance rateCurrInst = CurrencyInst.get(Long.parseLong(rateCurIds[i])).getInstance(); final Instance accInst = Instance.get(accountOids[i]); final Object[] rateObj = getRateObject(_parameter, "_" + _postFix, i); final RateInfo rateInfo = getRateInfo4UI(_parameter, "_" + _postFix, i); final Type type = Type.get(Long.parseLong(types[i])); final boolean isDebitTrans = type.getUUID().equals(CIAccounting.TransactionPositionDebit.uuid); final BigDecimal rateAmount = ((BigDecimal) formater.parse(amounts[i])).setScale(2, RoundingMode.HALF_UP); final BigDecimal amount = Currency .convertToCurrency(_parameter, rateAmount, rateInfo, null, curInstance) .setScale(2, RoundingMode.HALF_UP); final PositionInfo pos = new PositionInfo(); _transInfo.addPosition(pos); pos.setType(type).setAccInst(accInst).setCurrInst(curInstance).setRateCurrInst(rateCurrInst) .setRate(rateObj).setRateAmount(isDebitTrans ? rateAmount.negate() : rateAmount) .setAmount(isDebitTrans ? amount.negate() : amount).setOrder(i) .setRemark(remarks == null ? null : remarks[i]) .setInstance(Instance.get(oidMap.get(rowKeys[i]))); if (labelLinkOids != null) { final Instance labelInst = Instance.get(labelLinkOids[i]); if (labelInst.isValid()) { pos.setLabelInst(labelInst) .setLabelRelType(_postFix.equalsIgnoreCase("Debit") ? CIAccounting.TransactionPositionDebit2LabelProject.getType() : CIAccounting.TransactionPositionCredit2LabelProject.getType()); } } if (docLinkOids != null) { final Instance docInst = Instance.get(docLinkOids[i]); if (docInst.isValid()) { final DocumentInfo docInfoTmp = new DocumentInfo(docInst); if (docInfoTmp.isSumsDoc()) { pos.setDocInst(docInst) .setDocRelType(_postFix.equalsIgnoreCase("Debit") ? CIAccounting.TransactionPositionDebit2SalesDocument.getType() : CIAccounting.TransactionPositionCredit2SalesDocument.getType()); } else { pos.setDocInst(docInst) .setDocRelType(_postFix.equalsIgnoreCase("Debit") ? CIAccounting.TransactionPositionDebit2PaymentDocument.getType() : CIAccounting.TransactionPositionCredit2PaymentDocument.getType()); } } } if (_executeRels) { final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.Account2AccountAbstract); queryBldr.addWhereAttrEqValue(CIAccounting.Account2AccountAbstract.FromAccountLink, accInst); final MultiPrintQuery multi = queryBldr.getPrint(); final SelectBuilder selAcc = SelectBuilder.get() .linkto(CIAccounting.Account2AccountAbstract.ToAccountLink).instance(); multi.addSelect(selAcc); multi.addAttribute(CIAccounting.Account2AccountAbstract.Numerator, CIAccounting.Account2AccountAbstract.Denominator, CIAccounting.Account2AccountAbstract.Config); multi.execute(); int y = 1; final int group = _transInfo.getNextGroup(); while (multi.next()) { final Instance instance = multi.getCurrentInstance(); final PositionInfo connPos = new PositionInfo(); connPos.setPosType(TransPosType.CONNECTION); final Collection<Accounting.Account2AccountConfig> configs = multi .getAttribute(CIAccounting.Account2AccountAbstract.Config); final boolean deactivatable = configs != null && configs.contains(Accounting.Account2AccountConfig.DEACTIVATABLE); final boolean confCheck = isDebitTrans && configs != null && configs.contains(Accounting.Account2AccountConfig.APPLY4DEBIT) || !isDebitTrans && configs != null && configs.contains(Accounting.Account2AccountConfig.APPLY4CREDIT); // if cannot be deactivated or selected in the UserInterface if (confCheck && (!deactivatable || acc2accOids != null && deactivatable && Arrays.asList(acc2accOids).contains(instance.getOid()))) { final BigDecimal numerator = new BigDecimal(multi .<Integer>getAttribute(CIAccounting.Account2AccountAbstract.Numerator)); final BigDecimal denominator = new BigDecimal(multi .<Integer>getAttribute(CIAccounting.Account2AccountAbstract.Denominator)); BigDecimal amount2 = amount.multiply(numerator).divide(denominator, BigDecimal.ROUND_HALF_UP); BigDecimal rateAmount2 = rateAmount.multiply(numerator).divide(denominator, BigDecimal.ROUND_HALF_UP); if (instance.getType().isCIType(CIAccounting.Account2AccountCosting)) { connPos.setType(type); } else if (instance.getType() .isCIType(CIAccounting.Account2AccountCostingInverse)) { if (type.getUUID().equals(CIAccounting.TransactionPositionDebit.uuid)) { connPos.setType(CIAccounting.TransactionPositionCredit.getType()); } else { connPos.setType(CIAccounting.TransactionPositionDebit.getType()); } amount2 = amount2.negate(); } else if (instance.getType().isCIType(CIAccounting.Account2AccountCredit)) { if (isDebitTrans) { connPos.setType(CIAccounting.TransactionPositionCredit.getType()); } else { connPos.setType(CIAccounting.TransactionPositionDebit.getType()); amount2 = amount2.negate(); rateAmount2 = rateAmount2.negate(); } } else if (instance.getType().isCIType(CIAccounting.Account2AccountDebit)) { if (isDebitTrans) { connPos.setType(CIAccounting.TransactionPositionDebit.getType()); amount2 = amount2.negate(); rateAmount2 = rateAmount2.negate(); } else { connPos.setType(CIAccounting.TransactionPositionCredit.getType()); } } if (connPos.getType() == null) { Create_Base.LOG.error("Missing definition"); } else { connPos.setOrder(i).setConnOrder(y).setGroupId(group) .setAccInst(multi.<Instance>getSelect(selAcc)).setCurrInst(curInstance) .setRateCurrInst(rateCurrInst).setRate(rateObj).setAmount(amount2) .setRateAmount(rateAmount2); _transInfo.addPosition(connPos); } y++; } } } } } } catch (final ParseException e) { throw new EFapsException(Transaction_Base.class, "insertPositions", e); } }
From source file:org.kuali.kpme.tklm.leave.summary.service.LeaveSummaryServiceImpl.java
private void assignPendingValuesToRow(LeaveSummaryRow lsr, String accrualCategory, List<LeaveBlock> pendingLeaveBlocks) { BigDecimal pendingAccrual = BigDecimal.ZERO.setScale(2); BigDecimal pendingRequests = BigDecimal.ZERO.setScale(2); if (CollectionUtils.isNotEmpty(pendingLeaveBlocks)) { for (LeaveBlock aLeaveBlock : pendingLeaveBlocks) { EarnCodeContract ec = HrServiceLocator.getEarnCodeService().getEarnCode(aLeaveBlock.getEarnCode(), aLeaveBlock.getLeaveLocalDate()); boolean usageFlag = ec != null && StringUtils.equals(ec.getAccrualBalanceAction(), HrConstants.ACCRUAL_BALANCE_ACTION.USAGE); if (LMConstants.USAGE_LEAVE_BLOCK_TYPES.contains(aLeaveBlock.getLeaveBlockType()) && LMConstants.PENDING_LEAVE_BLOCK_STATUS.contains(aLeaveBlock.getRequestStatus()) && usageFlag) { if ((StringUtils.isBlank(accrualCategory) && StringUtils.isBlank(aLeaveBlock.getAccrualCategory())) || (StringUtils.isNotBlank(aLeaveBlock.getAccrualCategory()) && StringUtils.equals(aLeaveBlock.getAccrualCategory(), accrualCategory))) { if (aLeaveBlock.getLeaveAmount().compareTo(BigDecimal.ZERO) >= 0) { pendingAccrual = pendingAccrual.add(aLeaveBlock.getLeaveAmount()); } else { pendingRequests = pendingRequests.add(aLeaveBlock.getLeaveAmount()); }//from w w w. j a v a2 s. c o m } } } } lsr.setPendingLeaveAccrual(pendingAccrual); lsr.setPendingLeaveRequests(pendingRequests.negate()); }
From source file:org.totschnig.myexpenses.activity.ExpenseEdit.java
public Money getAmount() { Account a = getCurrentAccount();/*from w ww . j av a2s. c om*/ if (a == null) return null; Money result = new Money(a.currency, 0L); BigDecimal amount = validateAmountInput(false); if (amount == null) { return result; } if (mType == EXPENSE) { amount = amount.negate(); } result.setAmountMajor(amount); return result; }
From source file:net.pms.util.Rational.java
/** * Returns a {@link Rational} whose value is {@code (this - value)}. * * @param value the value to be subtracted from this {@link Rational}. * @return The subtraction result.//from ww w . j a v a 2s . c om */ @Nullable public Rational subtract(@Nullable BigDecimal value) { if (value == null) { return null; } return add(value.negate()); }
From source file:com.healthmarketscience.jackcess.Column.java
/** * Writes a numeric value.//from w ww. j ava2 s . c om */ private void writeNumericValue(ByteBuffer buffer, Object value) throws IOException { Object inValue = value; try { BigDecimal decVal = toBigDecimal(value); inValue = decVal; boolean negative = (decVal.compareTo(BigDecimal.ZERO) < 0); if (negative) { decVal = decVal.negate(); } // write sign byte buffer.put(negative ? (byte) 0x80 : (byte) 0); // adjust scale according to this column type (will cause the an // ArithmeticException if number has too many decimal places) decVal = decVal.setScale(getScale()); // check precision if (decVal.precision() > getPrecision()) { throw new IOException( "Numeric value is too big for specified precision " + getPrecision() + ": " + decVal); } // convert to unscaled BigInteger, big-endian bytes byte[] intValBytes = decVal.unscaledValue().toByteArray(); int maxByteLen = getType().getFixedSize() - 1; if (intValBytes.length > maxByteLen) { throw new IOException("Too many bytes for valid BigInteger?"); } if (intValBytes.length < maxByteLen) { byte[] tmpBytes = new byte[maxByteLen]; System.arraycopy(intValBytes, 0, tmpBytes, (maxByteLen - intValBytes.length), intValBytes.length); intValBytes = tmpBytes; } if (buffer.order() != ByteOrder.BIG_ENDIAN) { fixNumericByteOrder(intValBytes); } buffer.put(intValBytes); } catch (ArithmeticException e) { throw (IOException) new IOException("Numeric value '" + inValue + "' out of range").initCause(e); } }