Example usage for java.math BigDecimal doubleValue

List of usage examples for java.math BigDecimal doubleValue

Introduction

In this page you can find the example usage for java.math BigDecimal doubleValue.

Prototype

@Override
public double doubleValue() 

Source Link

Document

Converts this BigDecimal to a double .

Usage

From source file:org.posterita.businesslogic.performanceanalysis.CustomPOSReportManager.java

public static TabularReport generateTabularReportGroupByDate(Properties ctx, String title, String subtitle,
        int account_id, Timestamp fromDate, Timestamp toDate, String salesGroup, String priceQtyFilter)
        throws OperationException {
    boolean isTaxDue = (account_id == Constants.TAX_DUE.intValue());
    boolean isTaxCredit = (account_id == Constants.TAX_CREDIT.intValue());

    NumberFormat formatter = new DecimalFormat("###,###,##0.00");

    String sql = SalesAnalysisReportManager.getTabularDataSetSQL(ctx, account_id, fromDate, toDate, salesGroup);
    ArrayList<Object[]> tmpData = ReportManager.getReportData(ctx, sql, true);
    String currency = POSTerminalManager.getDefaultSalesCurrency(ctx).getCurSymbol();

    ArrayList<Object[]> reportData = new ArrayList<Object[]>();
    Object[] data = null;// w ww.  j  a v a2 s .  co  m
    BigDecimal b = null;

    if (isTaxCredit || isTaxDue) {
        reportData.add(tmpData.remove(0));
        Iterator<Object[]> iter = tmpData.iterator();

        while (iter.hasNext()) {
            data = iter.next();

            if (data.length == 1) {
                b = (BigDecimal) data[0];
                data[0] = formatter.format(b.doubleValue());
            }

            reportData.add(data);
        }
    } else {
        //----------------------------------------------------------------------------------------------------------------------------------------------------------
        TreeMap<String, TabularReportRecordBean> map = new TreeMap<String, TabularReportRecordBean>();

        String productName = null;
        BigDecimal price = null;
        BigDecimal qty = null;

        TabularReportRecordBean bean = null;

        ArrayList<Object[]> reportData2 = new ArrayList<Object[]>();
        Object[] headers = tmpData.remove(0);

        //adding headers
        reportData2.add(new Object[] { headers[0],
                //headers[1],
                headers[2] + "(" + currency + ")", headers[3] });

        double totalAmt = 0.0d;
        int totalQty = 0;

        for (Object[] record : tmpData) {
            productName = (String) record[0];
            price = (BigDecimal) record[2];
            qty = (BigDecimal) record[3];

            totalAmt += price.doubleValue();
            totalQty += qty.intValue();

            bean = map.get(productName);

            if (bean == null) {
                bean = new TabularReportRecordBean();

                bean.setProductName(productName);
                bean.setDate("");
                bean.setPrice(price);
                bean.setQty(qty);
            } else {
                bean.setPrice(bean.getPrice().add(price));
                bean.setQty(bean.getQty().add(qty));
            }

            map.put(productName, bean);

        } //for 

        Collection<TabularReportRecordBean> c = map.values();

        for (TabularReportRecordBean tbean : c) {
            Object[] obj = new Object[] { tbean.getProductName(), tbean.getPrice(), tbean.getQty() };

            reportData2.add(obj);
        }

        reportData.add(reportData2.remove(0));

        Iterator<Object[]> iter = reportData2.iterator();

        while (iter.hasNext()) {
            data = iter.next();

            if (data.length > 2) {
                b = (BigDecimal) data[1];
                data[1] = formatter.format(b.doubleValue());
            }

            reportData.add(data);
        }

        reportData.add(new Object[] { "Total", "" + formatter.format(totalAmt), totalQty + "" });

    }

    //style for table
    String tableStyle = "display";
    //style for columns        
    String[] styles = new String[] { "string", "currency", "numeric" };

    if (isTaxCredit || isTaxDue) {
        styles = new String[] { "numeric" };
    }

    //constructing the table
    TabularReport tReport = new TabularReport(reportData);
    //tReport.setSortable(true);
    tReport.setHeaderStyle(styles);
    tReport.setStyle(tableStyle);
    tReport.setTitle(title);
    tReport.setSubtitle(subtitle);
    tReport.createReport();

    return tReport;
}

From source file:be.dataminded.nifi.plugins.util.JdbcCommon.java

public static long convertToAvroStream(final ResultSet rs, final OutputStream outStream, String recordName,
        ResultSetRowCallback callback, final int maxRows, boolean convertNames)
        throws SQLException, IOException {
    final Schema schema = createSchema(rs, recordName, convertNames);
    final GenericRecord rec = new GenericData.Record(schema);

    final DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema);
    try (final DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter)) {
        dataFileWriter.create(schema, outStream);

        final ResultSetMetaData meta = rs.getMetaData();
        final int nrOfColumns = meta.getColumnCount();
        long nrOfRows = 0;
        while (rs.next()) {
            if (callback != null) {
                callback.processRow(rs);
            }/*from   w ww  .  j av  a 2  s  .c  om*/
            for (int i = 1; i <= nrOfColumns; i++) {
                final int javaSqlType = meta.getColumnType(i);

                // Need to handle CLOB and BLOB before getObject() is called, due to ResultSet's maximum portability statement
                if (javaSqlType == CLOB) {
                    Clob clob = rs.getClob(i);
                    if (clob != null) {
                        long numChars = clob.length();
                        char[] buffer = new char[(int) numChars];
                        InputStream is = clob.getAsciiStream();
                        int index = 0;
                        int c = is.read();
                        while (c > 0) {
                            buffer[index++] = (char) c;
                            c = is.read();
                        }
                        rec.put(i - 1, new String(buffer));
                        clob.free();
                    } else {
                        rec.put(i - 1, null);
                    }
                    continue;
                }

                if (javaSqlType == BLOB) {
                    Blob blob = rs.getBlob(i);
                    if (blob != null) {
                        long numChars = blob.length();
                        byte[] buffer = new byte[(int) numChars];
                        InputStream is = blob.getBinaryStream();
                        int index = 0;
                        int c = is.read();
                        while (c > 0) {
                            buffer[index++] = (byte) c;
                            c = is.read();
                        }
                        ByteBuffer bb = ByteBuffer.wrap(buffer);
                        rec.put(i - 1, bb);
                        blob.free();
                    } else {
                        rec.put(i - 1, null);
                    }
                    continue;
                }

                final Object value = rs.getObject(i);

                if (value == null) {
                    rec.put(i - 1, null);

                } else if (javaSqlType == BINARY || javaSqlType == VARBINARY || javaSqlType == LONGVARBINARY
                        || javaSqlType == ARRAY) {
                    // bytes requires little bit different handling
                    byte[] bytes = rs.getBytes(i);
                    ByteBuffer bb = ByteBuffer.wrap(bytes);
                    rec.put(i - 1, bb);

                } else if (value instanceof Byte) {
                    // tinyint(1) type is returned by JDBC driver as java.sql.Types.TINYINT
                    // But value is returned by JDBC as java.lang.Byte
                    // (at least H2 JDBC works this way)
                    // direct put to avro record results:
                    // org.apache.avro.AvroRuntimeException: Unknown datum type java.lang.Byte
                    rec.put(i - 1, ((Byte) value).intValue());
                } else if (value instanceof Short) {
                    //MS SQL returns TINYINT as a Java Short, which Avro doesn't understand.
                    rec.put(i - 1, ((Short) value).intValue());
                } else if (value instanceof BigDecimal) {
                    // Avro can't handle BigDecimal as a number - it will throw an AvroRuntimeException such as: "Unknown datum type: java.math.BigDecimal: 38"
                    try {
                        int scale = meta.getScale(i);
                        BigDecimal bigDecimal = ((BigDecimal) value);
                        if (scale == 0) {
                            if (meta.getPrecision(i) < 10) {
                                rec.put(i - 1, bigDecimal.intValue());
                            } else {
                                rec.put(i - 1, bigDecimal.longValue());
                            }
                        } else {
                            rec.put(i - 1, bigDecimal.doubleValue());
                        }
                    } catch (Exception e) {
                        rec.put(i - 1, value.toString());
                    }
                } else if (value instanceof BigInteger) {
                    // Check the precision of the BIGINT. Some databases allow arbitrary precision (> 19), but Avro won't handle that.
                    // It the SQL type is BIGINT and the precision is between 0 and 19 (inclusive); if so, the BigInteger is likely a
                    // long (and the schema says it will be), so try to get its value as a long.
                    // Otherwise, Avro can't handle BigInteger as a number - it will throw an AvroRuntimeException
                    // such as: "Unknown datum type: java.math.BigInteger: 38". In this case the schema is expecting a string.
                    if (javaSqlType == BIGINT) {
                        int precision = meta.getPrecision(i);
                        if (precision < 0 || precision > MAX_DIGITS_IN_BIGINT) {
                            rec.put(i - 1, value.toString());
                        } else {
                            try {
                                rec.put(i - 1, ((BigInteger) value).longValueExact());
                            } catch (ArithmeticException ae) {
                                // Since the value won't fit in a long, convert it to a string
                                rec.put(i - 1, value.toString());
                            }
                        }
                    } else {
                        rec.put(i - 1, value.toString());
                    }

                } else if (value instanceof Number || value instanceof Boolean) {
                    if (javaSqlType == BIGINT) {
                        int precision = meta.getPrecision(i);
                        if (precision < 0 || precision > MAX_DIGITS_IN_BIGINT) {
                            rec.put(i - 1, value.toString());
                        } else {
                            rec.put(i - 1, value);
                        }
                    } else {
                        rec.put(i - 1, value);
                    }

                } else {
                    // The different types that we support are numbers (int, long, double, float),
                    // as well as boolean values and Strings. Since Avro doesn't provide
                    // timestamp types, we want to convert those to Strings. So we will cast anything other
                    // than numbers or booleans to strings by using the toString() method.
                    rec.put(i - 1, value.toString());
                }
            }
            dataFileWriter.append(rec);
            nrOfRows += 1;

            if (maxRows > 0 && nrOfRows == maxRows)
                break;
        }

        return nrOfRows;
    }
}

From source file:gdsc.smlm.ij.utils.Utils.java

/**
 * Round the double to the specified significant digits
 * /*from   w  w w  .j  av a 2s. c o m*/
 * @param d
 * @param significantDigits
 * @return
 */
public static String rounded(double d, int significantDigits) {
    if (Double.isInfinite(d) || Double.isNaN(d))
        return "" + d;
    BigDecimal bd = new BigDecimal(d);
    bd = bd.round(new MathContext(significantDigits));
    return "" + bd.doubleValue();
}

From source file:at.illecker.hama.hybrid.examples.summation.SummationBSP.java

static void printOutput(BSPJob job, BigDecimal sum) throws IOException {
    FileSystem fs = FileSystem.get(job.getConfiguration());
    FileStatus[] listStatus = fs.listStatus(FileOutputFormat.getOutputPath(job));
    for (FileStatus status : listStatus) {
        if (!status.isDir()) {
            try {
                SequenceFile.Reader reader = new SequenceFile.Reader(fs, status.getPath(),
                        job.getConfiguration());

                Text key = new Text();
                DoubleWritable value = new DoubleWritable();

                if (reader.next(key, value)) {
                    LOG.info("Output File: " + status.getPath());
                    LOG.info("key: '" + key + "' value: '" + value + "' expected: '" + sum.doubleValue() + "'");
                    Assert.assertEquals("Expected value: '" + sum.doubleValue() + "' != '" + value + "'",
                            sum.doubleValue(), value.get(), Math.pow(10, (DOUBLE_PRECISION * -1)));
                }//from  w  ww. j  a va  2 s . c o  m
                reader.close();

            } catch (IOException e) {
                if (status.getLen() > 0) {
                    System.out.println("Output File " + status.getPath());
                    FSDataInputStream in = fs.open(status.getPath());
                    IOUtils.copyBytes(in, System.out, job.getConfiguration(), false);
                    in.close();
                }
            }
        }
    }
    // fs.delete(FileOutputFormat.getOutputPath(job), true);
}

From source file:com.liferay.util.FileUtil.java

public static String getsize(File fileName) {
    String finalVal;//from   w w  w .j a  va  2  s  .c o m
    long filesize = fileName.length();
    BigDecimal size = new BigDecimal(filesize);
    BigDecimal byteVal = null;
    BigDecimal changedByteVal = null;
    finalVal = "";
    if (filesize <= 0) {
        finalVal = "";
    } else if (filesize < MEGA_BYTE) {
        byteVal = new BigDecimal(KILO_BYTE);
        if (size != null) {
            changedByteVal = size.divide(byteVal, MathContext.UNLIMITED);
            finalVal = Long.toString(Math.round(Math.ceil(changedByteVal.doubleValue()))) + " KB";
        }
    } else if (filesize < GIGA_BYTE) {
        byteVal = new BigDecimal(MEGA_BYTE);
        if (size != null) {
            changedByteVal = size.divide(byteVal, MathContext.UNLIMITED);
            finalVal = Long.toString(Math.round(Math.ceil(changedByteVal.doubleValue()))) + " MB";
        }
    } else if (filesize < TERA_BYTE) {
        byteVal = new BigDecimal(GIGA_BYTE);
        if (size != null) {
            changedByteVal = size.divide(byteVal, MathContext.UNLIMITED);
            finalVal = Long.toString(Math.round(Math.ceil(changedByteVal.doubleValue()))) + " GB";
        }
    } else {
        byteVal = new BigDecimal(TERA_BYTE);
        if (size != null) {
            changedByteVal = size.divide(byteVal, MathContext.UNLIMITED);
            finalVal = Long.toString(Math.round(Math.ceil(changedByteVal.doubleValue()))) + " TB";
        }
    }
    return finalVal;
}

From source file:org.bitcoin.client.BitcoinClient.java

/**
 * Rounds a double to the nearest dwo decimals, rounding UP.
 * Not proud of this code, but it works.
 *///  ww w.  ja va2  s .com
protected static double roundToTwoDecimals(double amount) {
    BigDecimal amountTimes100 = new BigDecimal(amount * 100 + 0.5);
    BigDecimal roundedAmountTimes100 = new BigDecimal(amountTimes100.intValue());
    BigDecimal roundedAmount = roundedAmountTimes100.divide(new BigDecimal(100.0));

    return roundedAmount.doubleValue();
}

From source file:edu.ku.brc.specify.config.LatLonConverter.java

/**
 * Converts BigDecimal to Decimal Degrees.
 * @param bd the DigDecimal to be converted.
 * @param degreesFMT indicates whether to include the degrees symbol
 * @return a 1 piece string//from   www . ja v a2 s.  c  o  m
 */
public static String convertToDDDDDD(final BigDecimal bd, final DEGREES_FORMAT degreesFMT,
        final DIRECTION direction, final int decimalLen, final boolean alwaysIncludeDir) {
    if (bd == null || bd.doubleValue() == 0.0) {
        return "0.0";
    }

    StringBuilder sb = new StringBuilder();

    sb.append(String.format("%" + decimalLen + "." + decimalLen + "f", bd.abs()));

    if (degreesFMT == DEGREES_FORMAT.Symbol) {
        sb.append("\u00B0");

    }
    if (degreesFMT == DEGREES_FORMAT.String || alwaysIncludeDir) {
        int inx = bd.doubleValue() < 0.0 ? 1 : 0;
        if (direction != DIRECTION.None) {
            sb.append(' ');
            sb.append(direction == DIRECTION.NorthSouth ? northSouth[inx] : eastWest[inx]);
        }
    }
    //return format(bd.abs()) + (degreesFMT == DEGREES_FORMAT.Symbol ? "\u00B0" : "");
    return sb.toString();
}

From source file:net.ceos.project.poi.annotated.core.CsvHandler.java

/**
 * Apply a big decimal value at the field.
 * /*  w ww .j  av  a  2s .c  om*/
 * @param value
 *            the value
 * @param formatMask
 *            the decorator mask
 * @param transformMask
 *            the transformation mask
 * @return false if problem otherwise true
 */
protected static String toBigDecimal(final BigDecimal value, final String formatMask,
        final String transformMask) {
    if (value != null) {
        Double dBigDecimal = value.doubleValue();
        if (StringUtils.isNotBlank(transformMask)) {
            // apply transformation mask
            DecimalFormat df = new DecimalFormat(transformMask);
            return df.format(dBigDecimal);

        } else if (StringUtils.isNotBlank(formatMask)) {
            // apply format mask
            DecimalFormat df = new DecimalFormat(formatMask);
            return df.format(dBigDecimal);

        } else {
            return value.toString(); // the exact value
        }
    }
    return StringUtils.EMPTY;
}

From source file:com.idylwood.utils.MathUtils.java

public static final double sumArbitraryPrecision(final double... values) {
    BigDecimal sum = new BigDecimal(0);
    for (int i = values.length; i-- != 0;)
        sum = sum.add(new BigDecimal(values[i]), MathContext.UNLIMITED);
    return sum.doubleValue();
}

From source file:org.posterita.businesslogic.performanceanalysis.CustomPOSReportManager.java

public static TabularReport generateTabularReport(Properties ctx, String title, String subtitle, int account_id,
        Timestamp fromDate, Timestamp toDate, String salesGroup, String priceQtyFilter)
        throws OperationException {
    String sql = SalesAnalysisReportManager.getTabularDataSetSQL(ctx, account_id, fromDate, toDate, salesGroup);
    ArrayList<Object[]> tmpData = ReportManager.getReportData(ctx, sql, true);
    String currency = POSTerminalManager.getDefaultSalesCurrency(ctx).getCurSymbol();

    ArrayList<Object[]> reportData = new ArrayList<Object[]>();
    //copying data from tmpData to reportData

    NumberFormat formatter = new DecimalFormat("###,###,##0.00");

    Iterator<Object[]> iter = tmpData.iterator();

    Object[] data = null;/*from  w w w.jav a  2  s. com*/
    Object[] headers = null;
    BigDecimal b, c = null;

    boolean isTaxDue = (account_id == Constants.TAX_DUE.intValue());
    boolean isTaxCredit = (account_id == Constants.TAX_CREDIT.intValue());

    if (isTaxCredit || isTaxDue) {
        //copying header
        headers = iter.next();

        reportData.add(new Object[] { headers[0] + "(" + currency + ")", });

        while (iter.hasNext()) {
            data = iter.next();

            if (data.length == 1) {
                b = (BigDecimal) data[0];
                data[0] = formatter.format(b.doubleValue());
            }

            reportData.add(data);
        }
    } else {
        //copying header
        headers = iter.next();

        reportData.add(new Object[] { headers[0], headers[1], headers[2] + "(" + currency + ")", headers[3] });

        double totalAmt = 0.0d;
        BigDecimal totalQty = Env.ZERO;

        while (iter.hasNext()) {
            data = iter.next();

            if (data.length > 2) {
                b = (BigDecimal) data[2];
                c = (BigDecimal) data[3];

                data[2] = formatter.format(b.doubleValue());

                totalAmt += b.doubleValue();
                totalQty = totalQty.add(c);

            }

            reportData.add(data);
        }

        reportData.add(new Object[] { "Total", "", formatter.format(totalAmt) + "", totalQty + "" });

    }

    //style for table
    String tableStyle = "display";
    //style for columns        
    String[] styles = new String[] { "string", "date", "currency", "numeric" };

    if (isTaxCredit || isTaxDue) {
        styles = new String[] { "numeric" };
    }

    //constructing the table
    TabularReport tReport = new TabularReport(reportData);
    //tReport.setSortable(true);
    tReport.setHeaderStyle(styles);
    tReport.setStyle(tableStyle);
    tReport.setTitle(title);
    tReport.setSubtitle(subtitle);
    tReport.createReport();

    return tReport;
}