Java Code Examples for java.math.BigDecimal#multiply()
The following examples show how to use
java.math.BigDecimal#multiply() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TextSplitter.java From DBus with Apache License 2.0 | 6 votes |
public BigDecimal stringToBigDecimal_assci(String str) { // Start with 1/65536 to compute the first digit. //String strUtf8 = new BigDecimal curPlace = ASSCI_ONE_PLACE; BigDecimal result = BigDecimal.ZERO; int len = Math.min(str.length(), MAX_CHARS); for (int i = 0; i < len; i++) { int ch = str.charAt(i); if (ch > 127) { ch = 127; } result = result.add(tryDivide(new BigDecimal(ch), curPlace)); // advance to the next less significant place. e.g., 1/(128^2) for the // second char. curPlace = curPlace.multiply(ASSCI_ONE_PLACE); } return result; }
Example 2
Source File: DecimalUtil.java From BlogManagePlatform with Apache License 2.0 | 6 votes |
/** * 批量相除,第一个数为被除数 * @see frodez.constant.settings.DefDecimal#PRECISION * @see frodez.constant.settings.DefDecimal#ROUND_MODE * @param normalized 是否进行标准化, true为进行标准化,false为不进行标准化 * @author Frodez * @date 2019-01-28 */ public static BigDecimal divide(boolean normalized, BigDecimal first, BigDecimal... args) { if (EmptyUtil.yes(args)) { throw new IllegalArgumentException(); } BigDecimal result = first; BigDecimal divider = args[0]; for (int i = 0; i < args.length; ++i) { divider = divider.multiply(args[i]); } result = result.divide(divider, DefDecimal.ROUND_MODE); if (normalized) { return DecimalUtil.normalize(result); } return result; }
Example 3
Source File: DecimalFormat.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
/** * Formats a BigDecimal to produce a string. * @param number The BigDecimal to format * @param result where the text is to be appended * @param delegate notified of locations of sub fields * @exception ArithmeticException if rounding is needed with rounding * mode being set to RoundingMode.UNNECESSARY * @return The formatted number string */ private StringBuffer format(BigDecimal number, StringBuffer result, FieldDelegate delegate) { if (multiplier != 1) { number = number.multiply(getBigDecimalMultiplier()); } boolean isNegative = number.signum() == -1; if (isNegative) { number = number.negate(); } synchronized(digitList) { int maxIntDigits = getMaximumIntegerDigits(); int minIntDigits = getMinimumIntegerDigits(); int maxFraDigits = getMaximumFractionDigits(); int minFraDigits = getMinimumFractionDigits(); int maximumDigits = maxIntDigits + maxFraDigits; digitList.set(isNegative, number, useExponentialNotation ? ((maximumDigits < 0) ? Integer.MAX_VALUE : maximumDigits) : maxFraDigits, !useExponentialNotation); return subformat(result, delegate, isNegative, false, maxIntDigits, minIntDigits, maxFraDigits, minFraDigits); } }
Example 4
Source File: GammaExperiments.java From big-math with MIT License | 6 votes |
public static BigDecimal factorialUsingSpougeCached(BigDecimal x, MathContext mathContext) { MathContext mc = new MathContext(mathContext.getPrecision() * 2, mathContext.getRoundingMode()); int a = mathContext.getPrecision() * 13 / 10; List<BigDecimal> constants = getSpougeFactorialConstants(a); BigDecimal bigA = BigDecimal.valueOf(a); boolean negative = false; BigDecimal factor = constants.get(0); for (int k = 1; k < a; k++) { BigDecimal bigK = BigDecimal.valueOf(k); factor = factor.add(constants.get(k).divide(x.add(bigK), mc), mc); negative = !negative; } BigDecimal result = pow(x.add(bigA, mc), x.add(BigDecimal.valueOf(0.5), mc), mc); result = result.multiply(exp(x.negate().subtract(bigA, mc), mc), mc); result = result.multiply(factor, mc); return result.round(mathContext); }
Example 5
Source File: DecimalFormat.java From JDKSourceCode1.8 with MIT License | 6 votes |
/** * Formats a BigDecimal to produce a string. * @param number The BigDecimal to format * @param result where the text is to be appended * @param delegate notified of locations of sub fields * @exception ArithmeticException if rounding is needed with rounding * mode being set to RoundingMode.UNNECESSARY * @return The formatted number string */ private StringBuffer format(BigDecimal number, StringBuffer result, FieldDelegate delegate) { if (multiplier != 1) { number = number.multiply(getBigDecimalMultiplier()); } boolean isNegative = number.signum() == -1; if (isNegative) { number = number.negate(); } synchronized(digitList) { int maxIntDigits = getMaximumIntegerDigits(); int minIntDigits = getMinimumIntegerDigits(); int maxFraDigits = getMaximumFractionDigits(); int minFraDigits = getMinimumFractionDigits(); int maximumDigits = maxIntDigits + maxFraDigits; digitList.set(isNegative, number, useExponentialNotation ? ((maximumDigits < 0) ? Integer.MAX_VALUE : maximumDigits) : maxFraDigits, !useExponentialNotation); return subformat(result, delegate, isNegative, false, maxIntDigits, minIntDigits, maxFraDigits, minFraDigits); } }
Example 6
Source File: SolarEventCalculator.java From Beauty-Compass with Apache License 2.0 | 6 votes |
/** * 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)); }
Example 7
Source File: DecimalFormat.java From jdk-1.7-annotated with Apache License 2.0 | 6 votes |
/** * Formats a BigDecimal to produce a string. * @param number The BigDecimal to format * @param result where the text is to be appended * @param delegate notified of locations of sub fields * @exception ArithmeticException if rounding is needed with rounding * mode being set to RoundingMode.UNNECESSARY * @return The formatted number string */ private StringBuffer format(BigDecimal number, StringBuffer result, FieldDelegate delegate) { if (multiplier != 1) { number = number.multiply(getBigDecimalMultiplier()); } boolean isNegative = number.signum() == -1; if (isNegative) { number = number.negate(); } synchronized(digitList) { int maxIntDigits = getMaximumIntegerDigits(); int minIntDigits = getMinimumIntegerDigits(); int maxFraDigits = getMaximumFractionDigits(); int minFraDigits = getMinimumFractionDigits(); int maximumDigits = maxIntDigits + maxFraDigits; digitList.set(isNegative, number, useExponentialNotation ? ((maximumDigits < 0) ? Integer.MAX_VALUE : maximumDigits) : maxFraDigits, !useExponentialNotation); return subformat(result, delegate, isNegative, false, maxIntDigits, minIntDigits, maxFraDigits, minFraDigits); } }
Example 8
Source File: WorkflowCancelServiceSupplychainImpl.java From axelor-open-suite with GNU Affero General Public License v3.0 | 5 votes |
public SaleOrder saleOrderLineProcess(Invoice invoice, InvoiceLine invoiceLine) throws AxelorException { SaleOrderLine saleOrderLine = invoiceLine.getSaleOrderLine(); if (saleOrderLine == null) { return null; } SaleOrder saleOrder = saleOrderLine.getSaleOrder(); // Update invoiced amount on sale order line BigDecimal invoicedAmountToAdd = invoiceLine.getExTaxTotal(); // If is it a refund invoice, so we negate the amount invoiced if (InvoiceToolService.isRefund(invoiceLine.getInvoice())) { invoicedAmountToAdd = invoicedAmountToAdd.negate(); } if (!invoice.getCurrency().equals(saleOrder.getCurrency()) && saleOrderLine.getCompanyExTaxTotal().compareTo(BigDecimal.ZERO) != 0) { // If the sale order currency is different from the invoice currency, use company currency to // calculate a rate. This rate will be applied to sale order line BigDecimal currentCompanyInvoicedAmount = invoiceLine.getCompanyExTaxTotal(); BigDecimal rate = currentCompanyInvoicedAmount.divide( saleOrderLine.getCompanyExTaxTotal(), 4, RoundingMode.HALF_UP); invoicedAmountToAdd = rate.multiply(saleOrderLine.getExTaxTotal()); } saleOrderLine.setAmountInvoiced( saleOrderLine.getAmountInvoiced().subtract(invoicedAmountToAdd)); return saleOrder; }
Example 9
Source File: BigMatrixImpl.java From astor with GNU General Public License v2.0 | 5 votes |
/** * Returns the determinant of this matrix. * * @return determinant * @throws InvalidMatrixException if matrix is not square */ public BigDecimal getDeterminant() throws InvalidMatrixException { if (!isSquare()) { throw new NonSquareMatrixException(getRowDimension(), getColumnDimension()); } if (isSingular()) { // note: this has side effect of attempting LU decomp if lu == null return ZERO; } else { BigDecimal det = (parity == 1) ? ONE : ONE.negate(); for (int i = 0; i < getRowDimension(); i++) { det = det.multiply(lu[i][i]); } return det; } }
Example 10
Source File: DataFormatter.java From lams with GNU General Public License v2.0 | 5 votes |
public InternalDecimalFormatWithScale(String pattern, DecimalFormatSymbols symbols) { df = new DecimalFormat(trimTrailingCommas(pattern), symbols); setExcelStyleRoundingMode(df); Matcher endsWithCommasMatcher = endsWithCommas.matcher(pattern); if (endsWithCommasMatcher.find()) { String commas = (endsWithCommasMatcher.group(1)); BigDecimal temp = BigDecimal.ONE; for (int i = 0; i < commas.length(); ++i) { temp = temp.multiply(ONE_THOUSAND); } divider = temp; } else { divider = null; } }
Example 11
Source File: MatrixOperations.java From JavaMainRepo with Apache License 2.0 | 5 votes |
public BigDecimal[][] multiplyScalar(BigDecimal[][] a, BigDecimal d) { BigDecimal c[][]; int rowsA = a.length; int colsA = a[0].length; c = new BigDecimal[rowsA][colsA]; for (int i = 0; i < rowsA; i++) for (int j = 0; j < colsA; j++) { c[i][j] = d.multiply(a[i][j]); } return c; }
Example 12
Source File: BasicBigDecimal.java From jdk8u-jdk with GNU General Public License v2.0 | 4 votes |
private static BigDecimal mult(BigDecimal v, double mul) { return v.multiply(new BigDecimal(mul)); }
Example 13
Source File: ImmutableDifficulty.java From bitcoin-verde with MIT License | 4 votes |
@Override public Difficulty multiplyBy(final double difficultyAdjustment) { final BigDecimal currentValue = _toBigDecimal(); final BigDecimal bigDecimal = currentValue.multiply(BigDecimal.valueOf(difficultyAdjustment)); return Difficulty.fromBigInteger(bigDecimal.toBigInteger()); }
Example 14
Source File: SHA512.java From RipplePower with Apache License 2.0 | 4 votes |
public long frac(double x) { double math_floor = Math.floor(x); BigDecimal intx = new BigDecimal(x - math_floor); intx = intx.multiply(BigDecimal.valueOf(0x100000000l)); return intx.longValue() | 0; }
Example 15
Source File: BalanceUtils.java From Upchain-wallet with GNU Affero General Public License v3.0 | 4 votes |
public static BigDecimal tokenToWei(BigDecimal number, int decimals) { BigDecimal weiFactor = BigDecimal.TEN.pow(decimals); return number.multiply(weiFactor); }
Example 16
Source File: LinearScaleTicks.java From nebula with Eclipse Public License 2.0 | 4 votes |
/** * Updates tick label for log scale. * @param min * @param max * @param length * the length of scale */ private void updateTickLabelForLogScale(double min, double max, int length) { if (min <= 0 || max <= 0) throw new IllegalArgumentException("the range for log scale must be in positive range"); boolean minBigger = max < min; double logMin = Math.log10(min); int minLogDigit = (int) Math.ceil(logMin); int maxLogDigit = (int) Math.ceil(Math.log10(max)); final BigDecimal minDec = BigDecimal.valueOf(min); BigDecimal tickStep = pow(10, minLogDigit - 1); BigDecimal firstPosition; if (minDec.remainder(tickStep).doubleValue() <= 0) { firstPosition = minDec.subtract(minDec.remainder(tickStep)); } else { if (minBigger) firstPosition = minDec.subtract(minDec.remainder(tickStep)); else firstPosition = minDec.subtract(minDec.remainder(tickStep)).add(tickStep); } // add min boolean minDateAdded = false; if (minDec.compareTo(firstPosition) == (minBigger ? 1 : -1)) { minDateAdded = addMinMaxTickInfo(min, length, true); } for (int i = minLogDigit; minBigger ? i >= maxLogDigit : i <= maxLogDigit; i += minBigger ? -1 : 1) { // if the range is too big skip minor ticks if (Math.abs(maxLogDigit - minLogDigit) > 20) { BigDecimal v = pow(10, i); if (v.doubleValue() > max) break; addTickInfo(v, max, logMin, length, i == minLogDigit, minDateAdded); } else { // must use BigDecimal because it involves equal comparison for (BigDecimal j = firstPosition; minBigger ? j.doubleValue() >= pow(10, i - 1).doubleValue() : j.doubleValue() <= pow(10, i).doubleValue(); j = minBigger ? j.subtract(tickStep) : j.add(tickStep)) { if (minBigger ? j.doubleValue() < max : j.doubleValue() > max) { break; } addTickInfo(j, max, logMin, length, j == firstPosition, minDateAdded); } tickStep = minBigger ? tickStep.divide(pow(10, 1)) : tickStep.multiply(pow(10, 1)); firstPosition = minBigger ? pow(10, i - 1) : tickStep.add(pow(10, i)); } } // add max if (minBigger ? max < tickLabelValues.get(tickLabelValues.size() - 1) : max > tickLabelValues.get(tickLabelValues.size() - 1)) { addMinMaxTickInfo(max, length, false); } }
Example 17
Source File: AddSubtractMultiplyDivide.java From spring-boot-cookbook with Apache License 2.0 | 4 votes |
public static void main(String[] args) { String q1 = "0.06 + 0.01 ="; String q2 = "1.0 - 0.42="; String q3 = "4.015 * 100="; String q4 = "303.1 / 1000="; NumberFormat percent = NumberFormat.getPercentInstance(); //建立百分比格式化用 percent.setMaximumFractionDigits(5); double v = 0.06 + 0.01; System.out.println(q1 + v + "==" + percent.format(v));//0.06 + 0.01 =0.06999999999999999==7% System.out.println(q2 + (1.0 - 0.42));//1.0 - 0.42=0.5800000000000001 System.out.println(q3 + (4.015 * 100));//4.015 * 100=401.49999999999994 System.out.println(q4 + (303.1 / 1000));//303.1 / 1000=0.30310000000000004 System.out.println("====================LINE===================="); //****BigDecimal中传入的double类型的数据,要为String类型,不然得到在BigDecimal仍然是不准确的double数据**** // BigDecimal addend = new BigDecimal(0.06); // BigDecimal augend = new BigDecimal(0.01); BigDecimal addend = new BigDecimal("0.06"); BigDecimal augend = new BigDecimal("0.01"); BigDecimal result = addend.add(augend); System.out.println(q1 + result.doubleValue() + "==" + percent.format(v));//0.06 + 0.01 =0.07==7% // BigDecimal minuend = new BigDecimal(1.0); // BigDecimal subtrahend = new BigDecimal(0.42); BigDecimal minuend = new BigDecimal("1.0"); BigDecimal subtrahend = new BigDecimal("0.42"); result = minuend.subtract(subtrahend); System.out.println(q2 + result.doubleValue());//1.0 - 0.42=0.58 // BigDecimal multiplicand = new BigDecimal(4.015); // BigDecimal multiplicator = new BigDecimal(100); BigDecimal multiplicand = new BigDecimal("4.015"); BigDecimal multiplicator = new BigDecimal(100); result = multiplicand.multiply(multiplicator); System.out.println(q3 + result.doubleValue());//4.015 * 100=401.5 // BigDecimal dividend = new BigDecimal(303.1); BigDecimal dividend = new BigDecimal("303.1"); BigDecimal divisor = new BigDecimal(1000); int scale = 10;//保留几位有效数字 result = dividend.divide(divisor, scale, RoundingMode.HALF_UP); System.out.println(q4 + result.doubleValue());//303.1 / 1000=0.3031 }
Example 18
Source File: CurrencyService.java From website with GNU Affero General Public License v3.0 | 4 votes |
public BigDecimal percentageValue(BigDecimal amount, Integer percent) { double percentDecimal = Double.valueOf(percent) / 100; return amount.multiply(BigDecimal.valueOf(percentDecimal)); }
Example 19
Source File: Multi.java From vscrawler with Apache License 2.0 | 4 votes |
@Override public Object operate(SyntaxNode left, SyntaxNode right, StringContext stringContext) { Object leftValue = left.calculate(stringContext); Object rightValue = right.calculate(stringContext); if (leftValue == null || rightValue == null) { throw new EvaluateException("operate is null,left: " + leftValue + " right:" + rightValue); } // 左右都不为空,开始计算 // step one think as number if (leftValue instanceof Number && rightValue instanceof Number) { // 都是整数,则执行整数除法 if (leftValue instanceof Integer && rightValue instanceof Integer) { return (Integer) leftValue * (Integer) rightValue; } // 包含小数,转double执行除法 if (leftValue instanceof Double || rightValue instanceof Double || leftValue instanceof Float || rightValue instanceof Float) { return ((Number) leftValue).doubleValue() * ((Number) rightValue).doubleValue(); } // 包含BigDecimal 转bigDecimal if (leftValue instanceof BigDecimal || rightValue instanceof BigDecimal) { if (leftValue instanceof BigDecimal && rightValue instanceof BigDecimal) { return ((BigDecimal) leftValue).multiply((BigDecimal) rightValue); } BigDecimal newLeft = XpathUtil.toBigDecimal((Number) leftValue); BigDecimal newRight = XpathUtil.toBigDecimal((Number) rightValue); return newLeft.multiply(newRight); } // 包含长整数,且不包含小数,全部转化为长整数计算 if (leftValue instanceof Long || rightValue instanceof Long) { return ((Number) leftValue).longValue() * ((Number) rightValue).longValue(); } // 兜底,用double执行计算 return ((Number) leftValue).doubleValue() * ((Number) rightValue).doubleValue(); } throw new EvaluateException( "multiply operate must with number parameter left:" + leftValue + " right:" + rightValue); }
Example 20
Source File: OpMultiply.java From java-technology-stack with MIT License | 4 votes |
/** * Implements the {@code multiply} operator directly here for certain types * of supported operands and otherwise delegates to any registered overloader * for types not supported here. * <p>Supported operand types: * <ul> * <li>numbers * <li>String and int ('abc' * 2 == 'abcabc') * </ul> */ @Override public TypedValue getValueInternal(ExpressionState state) throws EvaluationException { Object leftOperand = getLeftOperand().getValueInternal(state).getValue(); Object rightOperand = getRightOperand().getValueInternal(state).getValue(); if (leftOperand instanceof Number && rightOperand instanceof Number) { Number leftNumber = (Number) leftOperand; Number rightNumber = (Number) rightOperand; if (leftNumber instanceof BigDecimal || rightNumber instanceof BigDecimal) { BigDecimal leftBigDecimal = NumberUtils.convertNumberToTargetClass(leftNumber, BigDecimal.class); BigDecimal rightBigDecimal = NumberUtils.convertNumberToTargetClass(rightNumber, BigDecimal.class); return new TypedValue(leftBigDecimal.multiply(rightBigDecimal)); } else if (leftNumber instanceof Double || rightNumber instanceof Double) { this.exitTypeDescriptor = "D"; return new TypedValue(leftNumber.doubleValue() * rightNumber.doubleValue()); } else if (leftNumber instanceof Float || rightNumber instanceof Float) { this.exitTypeDescriptor = "F"; return new TypedValue(leftNumber.floatValue() * rightNumber.floatValue()); } else if (leftNumber instanceof BigInteger || rightNumber instanceof BigInteger) { BigInteger leftBigInteger = NumberUtils.convertNumberToTargetClass(leftNumber, BigInteger.class); BigInteger rightBigInteger = NumberUtils.convertNumberToTargetClass(rightNumber, BigInteger.class); return new TypedValue(leftBigInteger.multiply(rightBigInteger)); } else if (leftNumber instanceof Long || rightNumber instanceof Long) { this.exitTypeDescriptor = "J"; return new TypedValue(leftNumber.longValue() * rightNumber.longValue()); } else if (CodeFlow.isIntegerForNumericOp(leftNumber) || CodeFlow.isIntegerForNumericOp(rightNumber)) { this.exitTypeDescriptor = "I"; return new TypedValue(leftNumber.intValue() * rightNumber.intValue()); } else { // Unknown Number subtypes -> best guess is double multiplication return new TypedValue(leftNumber.doubleValue() * rightNumber.doubleValue()); } } if (leftOperand instanceof String && rightOperand instanceof Integer) { int repeats = (Integer) rightOperand; StringBuilder result = new StringBuilder(); for (int i = 0; i < repeats; i++) { result.append(leftOperand); } return new TypedValue(result.toString()); } return state.operate(Operation.MULTIPLY, leftOperand, rightOperand); }