List of usage examples for java.math BigDecimal stripTrailingZeros
public BigDecimal stripTrailingZeros()
From source file:org.yes.cart.payment.impl.PayPalProPaymentGatewayImpl.java
private NvpBuilder createAuthRequest(final Payment payment, final String paymentAction) { final NvpBuilder npvs = new NvpBuilder(); npvs.addRaw("PAYMENTACTION", paymentAction); npvs.addRaw("INVNUM", payment.getOrderShipment()); npvs.addRaw("CREDITCARDTYPE", payment.getCardType()); npvs.addRaw("ACCT", payment.getCardNumber()); npvs.addRaw("EXPDATE", payment.getCardExpireMonth() + payment.getCardExpireYear()); npvs.addRaw("CVV2", payment.getCardCvv2Code()); npvs.addRaw("AMT", payment.getPaymentAmount().setScale(2, RoundingMode.HALF_UP).toString()); npvs.addRaw("CURRENCYCODE", payment.getOrderCurrency()); int i = 0;/* www . j a v a 2 s .c o m*/ BigDecimal itemsNetTotal = Total.ZERO; BigDecimal ship = Total.ZERO; for (final PaymentLine item : payment.getOrderItems()) { if (item.isShipment()) { ship = item.getUnitPrice(); } else { final BigDecimal intQty = item.getQuantity().setScale(0, RoundingMode.CEILING); final String skuName; final BigDecimal qty; if (MoneyUtils.isFirstEqualToSecond(intQty, item.getQuantity())) { // integer qty skuName = item.getSkuName(); qty = intQty.stripTrailingZeros(); } else { // fractional qty skuName = item.getQuantity().toPlainString().concat("x ").concat(item.getSkuName()); qty = BigDecimal.ONE; } npvs.addEncoded("L_NUMBER" + i, item.getSkuCode().length() > ITEMSKU ? item.getSkuCode().substring(0, ITEMSKU - 1) + "~" : item.getSkuCode()); npvs.addEncoded("L_NAME" + i, skuName.length() > ITEMNAME ? skuName.substring(0, ITEMNAME - 1) + "~" : skuName); npvs.addRaw("L_QTY" + i, qty.stripTrailingZeros().toPlainString()); final BigDecimal itemNetAmount = item.getUnitPrice().multiply(item.getQuantity()) .subtract(item.getTaxAmount()).setScale(Total.ZERO.scale(), RoundingMode.HALF_UP); final BigDecimal itemNetPricePerAdjustedQty = itemNetAmount.divide(qty, Total.ZERO.scale(), BigDecimal.ROUND_HALF_UP); // Need to do this to overcome rounding final BigDecimal restoredNetAmount = itemNetPricePerAdjustedQty.multiply(qty) .setScale(Total.ZERO.scale(), BigDecimal.ROUND_HALF_UP); itemsNetTotal = itemsNetTotal.add(restoredNetAmount); // final BigDecimal taxUnit = MoneyUtils.isFirstBiggerThanSecond(item.getTaxAmount(), Total.ZERO) ? item.getTaxAmount().divide(qty, Total.ZERO.scale(), BigDecimal.ROUND_HALF_UP) : Total.ZERO; npvs.addRaw("L_AMT" + i, itemNetPricePerAdjustedQty.toPlainString()); // npvs.addRaw("L_TAXAMT" + i, taxUnit.toPlainString()); i++; } } final BigDecimal itemsAndShipping = itemsNetTotal.add(ship); final BigDecimal paymentNet = payment.getPaymentAmount().subtract(payment.getTaxAmount()); if (MoneyUtils.isFirstBiggerThanSecond(itemsAndShipping, paymentNet)) { npvs.addRaw("SHIPDISCAMT", paymentNet.subtract(itemsAndShipping).toPlainString()); } npvs.addRaw("ITEMAMT", itemsNetTotal.toPlainString()); npvs.addRaw("SHIPPINGAMT", ship.toPlainString()); npvs.addRaw("TAXAMT", payment.getTaxAmount().toPlainString()); if (payment.getBillingAddress() != null) { npvs.addEncoded("EMAIL", payment.getBillingEmail()); npvs.addEncoded("FIRSTNAME", payment.getBillingAddress().getFirstname()); npvs.addEncoded("LASTNAME", payment.getBillingAddress().getLastname()); npvs.addEncoded("STREET", payment.getBillingAddress().getAddrline1()); if (StringUtils.isNotBlank(payment.getBillingAddress().getAddrline2())) { npvs.addEncoded("STREET2", payment.getBillingAddress().getAddrline2()); } npvs.addEncoded("CITY", payment.getBillingAddress().getCity()); npvs.addEncoded("STATE", payment.getBillingAddress().getStateCode()); npvs.addEncoded("ZIP", payment.getBillingAddress().getStateCode()); npvs.addEncoded("COUNTRYCODE", payment.getBillingAddress().getCountryCode()); } if (payment.getShippingAddress() != null) { npvs.addEncoded("SHIPTONAME", payment.getShippingAddress().getFirstname() + " " + payment.getShippingAddress().getLastname()); npvs.addEncoded("SHIPTOSTREET", payment.getShippingAddress().getAddrline1()); if (StringUtils.isNotBlank(payment.getShippingAddress().getAddrline2())) { npvs.addEncoded("SHIPTOSTREET2", payment.getShippingAddress().getAddrline2()); } npvs.addEncoded("SHIPTOCITY", payment.getShippingAddress().getCity()); npvs.addEncoded("SHIPTOSTATE", payment.getShippingAddress().getStateCode()); npvs.addEncoded("SHIPTOZIP", payment.getShippingAddress().getStateCode()); npvs.addEncoded("SHIPTOCOUNTRY", payment.getShippingAddress().getCountryCode()); } return npvs; }
From source file:org.zuinnote.hadoop.office.format.common.converter.ExcelConverterSimpleSpreadSheetCellDAO.java
/*** * This provides another sample to infer schema in form of simple datatypes * (e.g. boolean, byte etc.). You might add as many sample as necessary to get a * precise schema.// w w w . j a va 2 s.com * * @param dataRow */ public void updateSpreadSheetCellRowToInferSchemaInformation(SpreadSheetCellDAO[] dataRow) { // check size of cell based on address // if necessary add more to schemaRow for (SpreadSheetCellDAO currentSpreadSheetCellDAO : dataRow) { boolean dataTypeFound = false; if (currentSpreadSheetCellDAO != null) { // add potential column to list int j = new CellAddress(currentSpreadSheetCellDAO.getAddress()).getColumn(); if (j >= this.schemaRow.size()) { // fill up for (int x = this.schemaRow.size(); x <= j; x++) { this.schemaRow.add(null); } } // check if boolean data type if ((currentSpreadSheetCellDAO.getFormattedValue() != null) && (!"".equals(currentSpreadSheetCellDAO.getFormattedValue()))) { // skip null value String currentCellValue = currentSpreadSheetCellDAO.getFormattedValue(); // check if boolean if (("TRUE".equals(currentCellValue)) || ("FALSE".equals(currentCellValue))) { dataTypeFound = true; if (this.schemaRow.get(j) != null) { // check if previous assumption was boolean if (!(this.schemaRow.get(j) instanceof GenericBooleanDataType)) { // if not then the type needs to be set to string this.schemaRow.set(j, new GenericStringDataType()); } // if yes then nothing todo (already boolean) } else { // we face this the first time this.schemaRow.set(j, new GenericBooleanDataType()); } } // check if timestamp using provided format if (!dataTypeFound) { if (this.dateTimeFormat != null) { // only if a format is specified Date theDate = this.dateTimeFormat.parse(currentCellValue, new ParsePosition(0)); if (theDate != null) { // we found indeed a date time dataTypeFound = true; if (this.schemaRow.get(j) != null) { // check if previous assumption was date if (!(this.schemaRow.get(j) instanceof GenericTimestampDataType)) { // if not then the type needs to be set to string this.schemaRow.set(j, new GenericStringDataType()); } } else { // we face this the first time this.schemaRow.set(j, new GenericTimestampDataType()); } } } } // check for timestamp using java.sql.Timestamp if (!dataTypeFound) { try { java.sql.Timestamp ts = java.sql.Timestamp.valueOf(currentCellValue); dataTypeFound = true; this.schemaRow.set(j, new GenericTimestampDataType()); } catch (IllegalArgumentException e) { LOG.warn( "Could not identify timestamp using TimeStamp.valueOf. Trying last resort Date parsing...."); } } // check if date data type if (!dataTypeFound) { Date theDate = this.dateFormat.parse(currentCellValue, new ParsePosition(0)); if (theDate != null) { // we have indeed a date dataTypeFound = true; if (this.schemaRow.get(j) != null) { // check if previous assumption was date if (!(this.schemaRow.get(j) instanceof GenericDateDataType)) { // if not then the type needs to be set to string this.schemaRow.set(j, new GenericStringDataType()); } } else { // we face this the first time this.schemaRow.set(j, new GenericDateDataType()); // check if it has a time component } } } // check if BigDecimal BigDecimal bd = (BigDecimal) this.decimalFormat.parse(currentCellValue, new ParsePosition(0)); if ((!dataTypeFound) && (bd != null)) { BigDecimal bdv = bd.stripTrailingZeros(); dataTypeFound = true; if (this.schemaRow.get(j) != null) { // check if previous assumption was a number // check if we need to upgrade to decimal if ((bdv.scale() > 0) && (this.schemaRow.get(j) instanceof GenericNumericDataType)) { // upgrade to decimal, if necessary if (!(this.schemaRow.get(j) instanceof GenericBigDecimalDataType)) { this.schemaRow.set(j, new GenericBigDecimalDataType(bdv.precision(), bdv.scale())); } else { if ((bdv.scale() > ((GenericBigDecimalDataType) this.schemaRow.get(j)) .getScale()) && (bdv.precision() > ((GenericBigDecimalDataType) this.schemaRow .get(j)).getPrecision())) { this.schemaRow.set(j, new GenericBigDecimalDataType(bdv.precision(), bdv.scale())); } else if (bdv.scale() > ((GenericBigDecimalDataType) this.schemaRow.get(j)) .getScale()) { // upgrade scale GenericBigDecimalDataType gbd = ((GenericBigDecimalDataType) this.schemaRow .get(j)); gbd.setScale(bdv.scale()); this.schemaRow.set(j, gbd); } else if (bdv.precision() > ((GenericBigDecimalDataType) this.schemaRow.get(j)) .getPrecision()) { // upgrade precision // new precision is needed to extend to max scale GenericBigDecimalDataType gbd = ((GenericBigDecimalDataType) this.schemaRow .get(j)); int newpre = bdv.precision() + (gbd.getScale() - bdv.scale()); gbd.setPrecision(newpre); this.schemaRow.set(j, gbd); } } } else { // check if we need to upgrade one of the integer types // if current is byte boolean isByte = false; boolean isShort = false; boolean isInt = false; boolean isLong = true; try { bdv.longValueExact(); isLong = true; bdv.intValueExact(); isInt = true; bdv.shortValueExact(); isShort = true; bdv.byteValueExact(); isByte = true; } catch (Exception e) { LOG.debug("Possible data types: Long: " + isLong + " Int: " + isInt + " Short: " + isShort + " Byte: " + isByte); } // if it was Numeric before we can ignore testing the byte case, here just for // completeness if ((isByte) && ((this.schemaRow.get(j) instanceof GenericByteDataType) || (this.schemaRow.get(j) instanceof GenericShortDataType) || (this.schemaRow.get(j) instanceof GenericIntegerDataType) || (this.schemaRow.get(j) instanceof GenericLongDataType))) { // if it was Byte before we can ignore testing the byte case, here just for // completeness } else if ((isShort) && ((this.schemaRow.get(j) instanceof GenericByteDataType))) { // upgrade to short this.schemaRow.set(j, new GenericShortDataType()); } else if ((isInt) && ((this.schemaRow.get(j) instanceof GenericShortDataType) || (this.schemaRow.get(j) instanceof GenericByteDataType))) { // upgrade to integer this.schemaRow.set(j, new GenericIntegerDataType()); } else if ((!isByte) && (!isShort) && (!isInt) && !((this.schemaRow.get(j) instanceof GenericLongDataType))) { // upgrade to long this.schemaRow.set(j, new GenericLongDataType()); } } } else { // we face it for the first time // determine value type if (bdv.scale() > 0) { this.schemaRow.set(j, new GenericBigDecimalDataType(bdv.precision(), bdv.scale())); } else { boolean isByte = false; boolean isShort = false; boolean isInt = false; boolean isLong = true; try { bdv.longValueExact(); isLong = true; bdv.intValueExact(); isInt = true; bdv.shortValueExact(); isShort = true; bdv.byteValueExact(); isByte = true; } catch (Exception e) { LOG.debug("Possible data types: Long: " + isLong + " Int: " + isInt + " Short: " + isShort + " Byte: " + isByte); } if (isByte) { this.schemaRow.set(j, new GenericByteDataType()); } else if (isShort) { this.schemaRow.set(j, new GenericShortDataType()); } else if (isInt) { this.schemaRow.set(j, new GenericIntegerDataType()); } else if (isLong) { this.schemaRow.set(j, new GenericLongDataType()); } } } } if (!dataTypeFound) { // otherwise string if (!(this.schemaRow.get(j) instanceof GenericStringDataType)) { this.schemaRow.set(j, new GenericStringDataType()); } } } else { // ignore null values } } } }
From source file:org.zuinnote.hadoop.office.format.common.converter.ExcelConverterSimpleSpreadSheetCellDAO.java
/** * Translate a data row according to the currently defined schema. * /*from w w w . j a v a2s. c om*/ * @param dataRow cells containing data * @return an array of objects of primitive datatypes (boolean, int, byte, etc.) * containing the data of datarow, null if dataRow does not fit into * schema. Note: single elements can be null depending on the original * Excel * */ public Object[] getDataAccordingToSchema(SpreadSheetCellDAO[] dataRow) { if (dataRow == null) { return new Object[this.schemaRow.size()]; } if (dataRow.length > this.schemaRow.size()) { LOG.warn("Data row is larger than schema. Will return String for everything that is not specified. "); } List<Object> returnList = new ArrayList<>(); for (int i = 0; i < this.schemaRow.size(); i++) { // fill up with schema rows returnList.add(null); } for (int i = 0; i < dataRow.length; i++) { SpreadSheetCellDAO currentCell = dataRow[i]; if (currentCell != null) { // determine real position int j = new CellAddress(currentCell.getAddress()).getColumn(); if (j >= returnList.size()) { // fill up for (int x = returnList.size(); x <= j; x++) { returnList.add(null); } } GenericDataType applyDataType = null; if (j >= this.schemaRow.size()) { LOG.warn("No further schema row for column defined: " + String.valueOf(j) + ". Will assume String."); } else { applyDataType = this.schemaRow.get(j); } if (applyDataType == null) { returnList.set(j, currentCell.getFormattedValue()); } else if (applyDataType instanceof GenericStringDataType) { returnList.set(j, currentCell.getFormattedValue()); } else if (applyDataType instanceof GenericBooleanDataType) { if (!"".equals(currentCell.getFormattedValue())) { if (currentCell.getFormattedValue().equalsIgnoreCase("true") || currentCell.getFormattedValue().equalsIgnoreCase("false")) { returnList.set(j, Boolean.valueOf(currentCell.getFormattedValue())); } } } else if (applyDataType instanceof GenericTimestampDataType) { if (!"".equals(currentCell.getFormattedValue())) { boolean timestampFound = false; if (this.dateTimeFormat != null) { // check first dateTimeFormat Date theDate = this.dateTimeFormat.parse(currentCell.getFormattedValue(), new ParsePosition(0)); if (theDate != null) { returnList.set(j, new java.sql.Timestamp(theDate.getTime())); timestampFound = true; } else { returnList.set(j, null); LOG.warn( "Could not identify timestamp using Date.parse using provided dateTime format. Trying Timestamp.valueOf. Original value: " + currentCell.getFormattedValue()); } } if (!timestampFound) { try { returnList.set(j, java.sql.Timestamp.valueOf(currentCell.getFormattedValue())); timestampFound = true; } catch (IllegalArgumentException e) { returnList.set(j, null); LOG.warn( "Could not identify timestamp using TimeStamp.valueOf. Trying last resort Date parsing. Original value: " + currentCell.getFormattedValue()); } } if (!timestampFound) { Date theDate = this.dateFormat.parse(currentCell.getFormattedValue(), new ParsePosition(0)); if (theDate != null) { returnList.set(j, new java.sql.Timestamp(theDate.getTime())); } else { returnList.set(j, null); LOG.warn( "Could not identify timestamp using Date.parse using provided date format"); } } } } else if (applyDataType instanceof GenericDateDataType) { if (!"".equals(currentCell.getFormattedValue())) { Date theDate = this.dateFormat.parse(currentCell.getFormattedValue(), new ParsePosition(0)); if (theDate != null) { returnList.set(j, theDate); } else { returnList.set(j, null); } } } else if (applyDataType instanceof GenericNumericDataType) { if (!"".equals(currentCell.getFormattedValue())) { BigDecimal bd = null; try { if (!"".equals(currentCell.getFormattedValue())) { // check scientific notation if (currentCell.getFormattedValue().toUpperCase().contains("E")) { // parse scientific notation // remove any characters that could cause issues String sanitizedCellContent = currentCell.getFormattedValue().replace(",", "."); bd = new BigDecimal(sanitizedCellContent); } else { bd = (BigDecimal) this.decimalFormat.parse(currentCell.getFormattedValue()); } } } catch (ParseException p) { LOG.warn( "Could not parse decimal in spreadsheet cell, although type was detected as decimal"); } if (bd != null) { BigDecimal bdv = bd.stripTrailingZeros(); if (applyDataType instanceof GenericByteDataType) { returnList.set(j, (byte) bdv.byteValueExact()); } else if (applyDataType instanceof GenericShortDataType) { returnList.set(j, (short) bdv.shortValueExact()); } else if (applyDataType instanceof GenericIntegerDataType) { returnList.set(j, (int) bdv.intValueExact()); } else if (applyDataType instanceof GenericLongDataType) { returnList.set(j, (long) bdv.longValueExact()); } else if (applyDataType instanceof GenericDoubleDataType) { returnList.set(j, (double) bdv.doubleValue()); } else if (applyDataType instanceof GenericFloatDataType) { returnList.set(j, (float) bdv.floatValue()); } else if (applyDataType instanceof GenericBigDecimalDataType) { returnList.set(j, bd); } else { returnList.set(j, null); } } } } else { returnList.set(j, null); LOG.warn("Could not convert object in spreadsheet cellrow. Did you add a new datatype?"); } } } Object[] result = new Object[returnList.size()]; returnList.toArray(result); return result; }
From source file:uk.ac.leeds.ccg.andyt.generic.visualisation.charts.Generic_ScatterPlotAndLinearRegression.java
/** * @param regressionParameters regressionParameters[0] is the y axis * intercept; regressionParameters[1] is the change in y relative to x * (gradient or slope); regressionParameters[2] is the rank correlation * coefficient (RSquare); regressionParameters[3] is data[0].length. *///from ww w . j a v a 2s . co m protected void drawLegend(double[] regressionParameters) { // int[] result = new int[3]; int newLegendWidth = 0; int newLegendHeight = 0; // int legendExtraWidthLeft = 0; // int legendExtraWidthRight = 0; int textHeight = getTextHeight(); int legendExtraHeightBottom = textHeight; int legendStartRow = getDataEndRow() + getxAxisHeight(); // int legendStartRow = this.dataEndRow + this.xAxisHeight / 2; int symbolRow; int row; int symbolCol; int col; int symbolWidth = 10; // Legend Title setPaint(Color.DARK_GRAY); int legendItemWidth = 0; String text = "Legend"; int textWidth = getTextWidth(text); newLegendHeight += textHeight; row = legendStartRow + newLegendHeight; //col = dataStartCol - yAxisWidth; col = textHeight; legendItemWidth += textWidth; newLegendWidth = Math.max(newLegendWidth, legendItemWidth); drawString(text, col, row); Point2D.Double point = new Point2D.Double(); // Point marker legendItemWidth = 0; newLegendHeight += textHeight; symbolRow = legendStartRow + newLegendHeight; legendItemWidth += symbolWidth; symbolCol = col + symbolWidth / 2; point.setLocation(symbolCol, symbolRow); setPaint(Color.DARK_GRAY); draw(point); row += ((3 * textHeight) / 2) - 2; newLegendHeight += (textHeight / 2) - 2; col += symbolWidth + 4; setPaint(Color.GRAY); text = "Data Point"; textWidth = getTextWidth(text); legendItemWidth += textWidth; newLegendWidth = Math.max(newLegendWidth, legendItemWidth); drawString(text, col, row); // Y = X line setPaint(Color.LIGHT_GRAY); //int itemSymbolWidth = (symbolCol + symbolWidth / 2) - (symbolCol - symbolWidth / 2); //legendItemWidth = itemSymbolWidth; //legendItemWidth = symbolWidth + 4; symbolRow += textHeight; draw(new Line2D.Double(symbolCol - symbolWidth / 2, (symbolRow + textHeight / 2) - 2, symbolCol + symbolWidth / 2, (symbolRow - textHeight / 2) + 2)); setPaint(Color.GRAY); row += textHeight; text = "Y = X"; textWidth = getTextWidth(text); drawString(text, col, row); legendItemWidth = textWidth; newLegendWidth = Math.max(newLegendWidth, legendItemWidth); newLegendHeight += textHeight + 4; // Regression line setPaint(Color.DARK_GRAY); legendItemWidth = symbolWidth + 4; symbolRow += textHeight; row += textHeight; draw(new Line2D.Double(symbolCol - symbolWidth / 2, (symbolRow + textHeight / 2) - 2, symbolCol + symbolWidth / 2, (symbolRow - textHeight / 2) + 2)); setPaint(Color.GRAY); // Y = mX + c // generalise m int scale = 4; BigDecimal m; if (Double.isNaN(regressionParameters[1])) { m = BigDecimal.ZERO; } else { m = BigDecimal.valueOf(regressionParameters[1]); } RoundingMode roundingMode = getRoundingMode(); m = m.setScale(scale, roundingMode); m = m.stripTrailingZeros(); // m = Generic_BigDecimal.roundStrippingTrailingZeros( // m, // decimalPlacePrecision, // _RoundingMode); BigDecimal c; if (Double.isNaN(regressionParameters[0])) { c = BigDecimal.ZERO; } else { c = BigDecimal.valueOf(regressionParameters[0]); } c = c.setScale(scale, roundingMode); c = c.stripTrailingZeros(); BigDecimal rsquare; if (Double.isNaN(regressionParameters[2])) { rsquare = BigDecimal.ZERO; } else { rsquare = BigDecimal.valueOf(regressionParameters[2]); } rsquare = rsquare.setScale(3, roundingMode); rsquare = rsquare.stripTrailingZeros(); String equation; if (c.compareTo(BigDecimal.ZERO) != -1) { equation = "Y = (" + m + " * X) + " + c + ""; } else { equation = "Y = (" + m + " * X) - " + c.negate() + ""; } drawString(equation, col, row); textWidth = getTextWidth(equation); legendItemWidth += textWidth; newLegendWidth = Math.max(newLegendWidth, legendItemWidth); newLegendHeight += textHeight; // Rsquare component String rsquare_String = "RSquare = " + rsquare; textWidth = getTextWidth(rsquare_String); legendItemWidth = textWidth; row += textHeight; drawString(rsquare_String, col, row); //setLegendHeight(row - legendStartRow); newLegendWidth = Math.max(newLegendWidth, legendItemWidth); newLegendHeight += (2 * textHeight); int imageWidth = getImageWidth(); int dataWidth = getDataWidth(); int extraWidthLeft = getExtraWidthLeft(); if (newLegendWidth > getLegendWidth()) { //int diff = newLegendWidth - legendWidth; if (newLegendWidth > imageWidth) { setImageWidth(newLegendWidth); setExtraWidthRight(newLegendWidth - extraWidthLeft - dataWidth); } setLegendWidth(newLegendWidth); } int extraHeightBottom = getExtraHeightBottom(); if (newLegendHeight > getLegendHeight()) { //int diff = newLegendHeight - legendHeight; //int heightForLegend = legendStartRow - dataStartRow + newLegendHeight; int newExtraHeightBottom = newLegendHeight + getxAxisHeight(); if (newExtraHeightBottom > extraHeightBottom) { int diff2 = newExtraHeightBottom - extraHeightBottom; setExtraHeightBottom(newExtraHeightBottom); setImageHeight(getImageHeight() + diff2); } setLegendHeight(newLegendHeight); } // result[0] = legendExtraWidthLeft; // result[1] = legendExtraWidthRight; // result[2] = legendExtraHeightBottom; // return result; }