List of usage examples for java.math BigDecimal subtract
public BigDecimal subtract(BigDecimal subtrahend)
From source file:com.fanniemae.ezpie.common.StringUtilities.java
public static String formatAsNumber(double value) { BigDecimal valueOf = BigDecimal.valueOf(value); BigDecimal integerPart = BigDecimal.valueOf(valueOf.longValue()); BigDecimal fractional = valueOf.subtract(integerPart); String fraction = fractional.toPlainString(); int indexOfDot = fraction.indexOf('.') + 1; String sign = fraction.startsWith("-") ? "-" : ""; fraction = fraction.length() > indexOfDot ? fraction.substring(indexOfDot) : fraction; if (fraction.equals("0")) { return MessageFormat.format("{0}{1}", sign, integerPart.toPlainString(), fraction); } else {/*from www.j ava2 s. co m*/ return MessageFormat.format("{0}{1}.{2}", sign, integerPart.toPlainString(), fraction); } }
From source file:org.apache.hadoop.hive.common.type.HiveIntervalDayTime.java
public static HiveIntervalDayTime valueOf(String strVal) { HiveIntervalDayTime result = null;//from w w w . ja va 2 s. c o m if (strVal == null) { throw new IllegalArgumentException("Interval day-time string was null"); } Matcher patternMatcher = PATTERN_MATCHER.get(); patternMatcher.reset(strVal); if (patternMatcher.matches()) { // Parse out the individual parts try { // Sign - whether interval is positive or negative int sign = 1; String field = patternMatcher.group(1); if (field != null && field.equals("-")) { sign = -1; } int days = sign * IntervalDayTimeUtils.parseNumericValueWithRange("day", patternMatcher.group(2), 0, Integer.MAX_VALUE); byte hours = (byte) (sign * IntervalDayTimeUtils.parseNumericValueWithRange("hour", patternMatcher.group(3), 0, 23)); byte minutes = (byte) (sign * IntervalDayTimeUtils.parseNumericValueWithRange("minute", patternMatcher.group(4), 0, 59)); int seconds = 0; int nanos = 0; field = patternMatcher.group(5); if (field != null) { BigDecimal bdSeconds = new BigDecimal(field); if (bdSeconds.compareTo(IntervalDayTimeUtils.MAX_INT_BD) > 0) { throw new IllegalArgumentException("seconds value of " + bdSeconds + " too large"); } seconds = sign * bdSeconds.intValue(); nanos = sign * bdSeconds.subtract(new BigDecimal(bdSeconds.toBigInteger())) .multiply(IntervalDayTimeUtils.NANOS_PER_SEC_BD).intValue(); } result = new HiveIntervalDayTime(days, hours, minutes, seconds, nanos); } catch (Exception err) { throw new IllegalArgumentException("Error parsing interval day-time string: " + strVal, err); } } else { throw new IllegalArgumentException( "Interval string does not match day-time format of 'd h:m:s.n': " + strVal); } return result; }
From source file:client.Pi.java
/** * Compute the value, in radians, of the arctangent of * the inverse of the supplied integer to the specified * number of digits after the decimal point. The value * is computed using the power series expansion for the * arc tangent://from w ww.j a v a 2 s .c om * * arctan(x) = x - (x^3)/3 + (x^5)/5 - (x^7)/7 + * (x^9)/9 ... */ public static BigDecimal arctan(int inverseX, int scale) { BigDecimal result, numer, term; BigDecimal invX = BigDecimal.valueOf(inverseX); BigDecimal invX2 = BigDecimal.valueOf(inverseX * inverseX); numer = BigDecimal.ONE.divide(invX, scale, roundingMode); result = numer; int i = 1; do { numer = numer.divide(invX2, scale, roundingMode); int denom = 2 * i + 1; term = numer.divide(BigDecimal.valueOf(denom), scale, roundingMode); if ((i % 2) != 0) { result = result.subtract(term); } else { result = result.add(term); } i++; } while (term.compareTo(BigDecimal.ZERO) != 0); return result; }
From source file:org.kalypso.ui.wizards.results.ResultSldHelper.java
/** * sets the parameters for the colormap of an isoline *///from ww w. j av a2s . com private static void configureLineSymbolizer(final SurfaceLineSymbolizer symbolizer, final BigDecimal minValue, final BigDecimal maxValue) throws FilterEvaluationException { final LineColorMap templateColorMap = symbolizer.getColorMap(); final LineColorMap newColorMap = new LineColorMap_Impl(); // retrieve stuff from template-entries final LineColorMapEntry fromEntry = templateColorMap.findEntry("from", null); //$NON-NLS-1$ final LineColorMapEntry toEntry = templateColorMap.findEntry("to", null); //$NON-NLS-1$ final LineColorMapEntry fatEntry = templateColorMap.findEntry("fat", null); //$NON-NLS-1$ final Color fromColor = fromEntry.getStroke().getStroke(null); final Color toColor = toEntry.getStroke().getStroke(null); final double opacity = fromEntry.getStroke().getOpacity(null); final double normalWidth = fromEntry.getStroke().getWidth(null); final double fatWidth = fatEntry.getStroke().getWidth(null); // defines which isolines are drawn with a fat line final double fatValue = fatEntry.getQuantity(null); // TODO: get setep / scale from quantity // get rounded values below min and above max (rounded by first decimal) // as a first try we will generate isolines using class steps of 0.1 // later, the classes will be done by using user defined class steps. // for that we fill an array of calculated (later user defined values) from max to min final BigDecimal minDecimal = minValue.setScale(1, BigDecimal.ROUND_FLOOR); final BigDecimal maxDecimal = maxValue.setScale(1, BigDecimal.ROUND_CEILING); final BigDecimal stepWidth = new BigDecimal(0.1).setScale(1, BigDecimal.ROUND_HALF_UP); final int numOfClasses = (maxDecimal.subtract(minDecimal).divide(stepWidth)).intValue() + 1; for (int currentClass = 0; currentClass < numOfClasses; currentClass++) { final double currentValue = minDecimal.doubleValue() + currentClass * stepWidth.doubleValue(); Color lineColor; if (fromColor == toColor) lineColor = fromColor; else lineColor = interpolateColor(fromColor, toColor, currentClass, numOfClasses); final double strokeWidth; if (currentValue % fatValue == 0) strokeWidth = fatWidth; else strokeWidth = normalWidth; final Stroke stroke = StyleFactory.createStroke(lineColor, strokeWidth, opacity); final ParameterValueType label = StyleFactory.createParameterValueType("Isolinie " + currentClass); //$NON-NLS-1$ final ParameterValueType quantity = StyleFactory.createParameterValueType(currentValue); final LineColorMapEntry colorMapEntry = new LineColorMapEntry_Impl(stroke, label, quantity); newColorMap.addColorMapClass(colorMapEntry); } symbolizer.setColorMap(newColorMap); }
From source file:org.openmrs.module.openhmis.cashier.api.util.RoundingUtil.java
private static BigDecimal calculateRoundingValue(Bill bill, CashierOptions options, BillLineItem roundingLineItem) { List<BillLineItem> lineItems = bill.getLineItems(); BigDecimal itemTotal = new BigDecimal(0); if (lineItems == null) { return BigDecimal.ZERO; }//from w w w . ja v a 2 s . c o m for (BillLineItem lineItem : lineItems) { if (lineItem != null && !lineItem.getVoided()) { if (roundingLineItem == null || !roundingLineItem.equals(lineItem)) { itemTotal = itemTotal.add(lineItem.getTotal()); } } } return itemTotal .subtract(RoundingUtil.round(itemTotal, options.getRoundToNearest(), options.getRoundingMode())); }
From source file:lu.lippmann.cdb.graph.renderer.CadralEdgeColorTransformer.java
private static Color rangeColor(Color colorMin, Color colorMax, BigDecimal grow, BigDecimal minValue, BigDecimal maxValue) {/*from w w w . j ava 2 s . c om*/ BigDecimal colorValue = grow; if (colorValue == null) { return Color.LIGHT_GRAY; } if (maxValue.compareTo(minValue) < 0) { return rangeColor(colorMin, colorMax, grow, maxValue, minValue); } else { int rMax = colorMax.getRed(); int gMax = colorMax.getGreen(); int bMax = colorMax.getBlue(); double color = 0.0; color = 255.0 - grow.subtract(minValue).doubleValue() * 255.0 / maxValue.subtract(minValue).doubleValue(); int r = rMax + (int) ((255 - rMax) * color / 255.0); int g = gMax + (int) ((255 - gMax) * color / 255.0); int b = bMax + (int) ((255 - bMax) * color / 255.0); if (r > 192 && g > 192 && b > 192) return Color.LIGHT_GRAY; return new Color(r, g, b); } }
From source file:com.willetinc.hadoop.mapreduce.dynamodb.BinarySplitter.java
/** * Return the string encoded in a BigDecimal. Repeatedly multiply the input * value by 16; the integer portion after such a multiplication represents a * single character in base 16. Convert that back into a char and create a * string out of these until we have no data left. * //from w w w. j a va 2 s .c o m * @throws IOException */ static byte[] bigDecimalToByteArray(BigDecimal bd, int maxBytes) { BigDecimal cur = bd.stripTrailingZeros(); ByteArrayOutputStream sb = new ByteArrayOutputStream(); try { byte[] curCodePoint = new byte[1]; for (int numConverted = 0; numConverted < maxBytes; numConverted++) { cur = cur.multiply(ONE_PLACE); curCodePoint[0] = cur.byteValue(); if (0x0 == curCodePoint[0]) { break; } cur = cur.subtract(new BigDecimal(new BigInteger(curCodePoint))); sb.write(curCodePoint); } } catch (IOException e) { LOG.error("Error writing byte array", e); } return sb.toByteArray(); }
From source file:org.openbravo.advpaymentmngt.process.FIN_ExecutePayment.java
private static void updatePaymentAmounts(FIN_Payment payment) { for (FIN_PaymentDetail pDetail : payment.getFINPaymentDetailList()) { for (FIN_PaymentScheduleDetail psd : pDetail.getFINPaymentScheduleDetailList()) { if (psd.getInvoicePaymentSchedule() != null) { BusinessPartner bPartner = psd.getInvoicePaymentSchedule().getInvoice().getBusinessPartner(); BigDecimal creditUsed = bPartner.getCreditUsed(); BigDecimal amountWithSign = psd.getInvoicePaymentSchedule().getInvoice().isSalesTransaction() ? psd.getAmount() : psd.getAmount().negate(); creditUsed = creditUsed.subtract(amountWithSign); bPartner.setCreditUsed(creditUsed); OBDal.getInstance().save(bPartner); FIN_AddPayment.updatePaymentScheduleAmounts(pDetail, psd.getInvoicePaymentSchedule(), psd.getAmount(), psd.getWriteoffAmount()); }//from w w w .ja v a 2 s .com if (psd.getOrderPaymentSchedule() != null) { FIN_AddPayment.updatePaymentScheduleAmounts(pDetail, psd.getOrderPaymentSchedule(), psd.getAmount(), psd.getWriteoffAmount()); } if (pDetail.isPrepayment() && psd.getOrderPaymentSchedule() == null && psd.getInvoicePaymentSchedule() == null) { // This PSD is credit BusinessPartner bPartner = psd.getPaymentDetails().getFinPayment().getBusinessPartner(); BigDecimal creditUsed = bPartner.getCreditUsed(); BigDecimal amountWithSign = psd.getPaymentDetails().getFinPayment().isReceipt() ? psd.getAmount() : psd.getAmount().negate(); creditUsed = creditUsed.subtract(amountWithSign); bPartner.setCreditUsed(creditUsed); OBDal.getInstance().save(bPartner); } } } // When credit is used (consumed) we compensate so_creditused as this amount is already // included in the payment details. Credit consumed should not affect to so_creditused if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 0 && payment.getUsedCredit().compareTo(BigDecimal.ZERO) != 0) { BusinessPartner bp = payment.getBusinessPartner(); if (payment.isReceipt()) { bp.setCreditUsed(bp.getCreditUsed().add(payment.getUsedCredit())); } else { bp.setCreditUsed(bp.getCreditUsed().subtract(payment.getUsedCredit())); } OBDal.getInstance().save(bp); } }
From source file:Main.java
/** * Add two positive Duration objects./* w ww .j a va2 s . co m*/ * @param d1 The first Duration. * @param d2 The second Duration. * @return The sum of the two durations. */ private static Duration addPositiveDurations(Duration d1, Duration d2) { BigDecimal s1 = fractionalSeconds(d1); BigDecimal s2 = fractionalSeconds(d2); BigDecimal extraSeconds = s1.add(s2); Duration strip1 = stripFractionalSeconds(d1); Duration strip2 = stripFractionalSeconds(d2); Duration stripResult = strip1.add(strip2); if (extraSeconds.compareTo(BigDecimal.ONE) >= 0) { stripResult = stripResult.add(DURATION_1_SECOND); extraSeconds = extraSeconds.subtract(BigDecimal.ONE); } BigDecimal properSeconds = BigDecimal.valueOf(stripResult.getSeconds()).add(extraSeconds); return FACTORY.newDuration(true, BigInteger.valueOf(stripResult.getYears()), BigInteger.valueOf(stripResult.getMonths()), BigInteger.valueOf(stripResult.getDays()), BigInteger.valueOf(stripResult.getHours()), BigInteger.valueOf(stripResult.getMinutes()), properSeconds); }
From source file:org.apache.hadoop.hive.serde2.io.TimestampWritable.java
public static Timestamp decimalToTimestamp(BigDecimal d) { BigDecimal seconds = new BigDecimal(d.longValue()); long millis = d.multiply(new BigDecimal(1000)).longValue(); int nanos = d.subtract(seconds).multiply(new BigDecimal(1000000000)).intValue(); Timestamp t = new Timestamp(millis); t.setNanos(nanos);/* w w w. ja v a 2s .co m*/ return t; }