Example usage for java.math BigDecimal toString

List of usage examples for java.math BigDecimal toString

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns the string representation of this BigDecimal , using scientific notation if an exponent is needed.

Usage

From source file:org.apache.jackrabbit.core.persistence.util.BundleWriter.java

/**
 * Serializes a BigDecimal/*w ww .j a v  a2  s  .c om*/
 *
 * @param decimal the decimal number
 * @throws IOException in an I/O error occurs.
 */
private void writeDecimal(BigDecimal decimal) throws IOException {
    if (decimal == null) {
        out.writeBoolean(false);
    } else {
        out.writeBoolean(true);
        // TODO more efficient serialization format
        writeString(decimal.toString());
    }
}

From source file:org.openbravo.advpaymentmngt.ad_actionbutton.ProcessInvoice.java

private FieldProvider[] getCreditPayments(Invoice invoice) {
    FieldProvider[] data = FieldProviderFactory.getFieldProviderArray(creditPayments);
    String dateFormat = OBPropertiesProvider.getInstance().getOpenbravoProperties()
            .getProperty("dateFormat.java");
    SimpleDateFormat dateFormater = new SimpleDateFormat(dateFormat);

    BigDecimal pendingToPay = invoice.getGrandTotalAmount();
    try {//from ww  w .  j av a 2s.  c o m
        OBContext.setAdminMode(true);
        for (int i = 0; i < data.length; i++) {
            FieldProviderFactory.setField(data[i], "finCreditPaymentId", creditPayments.get(i).getId());
            FieldProviderFactory.setField(data[i], "documentNo", creditPayments.get(i).getDocumentNo());
            FieldProviderFactory.setField(data[i], "paymentDescription",
                    creditPayments.get(i).getDescription());
            if (creditPayments.get(i).getPaymentDate() != null) {
                FieldProviderFactory.setField(data[i], "documentDate",
                        dateFormater.format(creditPayments.get(i).getPaymentDate()).toString());
            }

            final BigDecimal outStandingAmt = creditPayments.get(i).getGeneratedCredit()
                    .subtract(creditPayments.get(i).getUsedCredit());
            FieldProviderFactory.setField(data[i], "outstandingAmount", outStandingAmt.toString());

            FieldProviderFactory.setField(data[i], "paymentAmount",
                    pendingToPay.compareTo(outStandingAmt) > 0 ? outStandingAmt.toString()
                            : (pendingToPay.compareTo(BigDecimal.ZERO) > 0 ? pendingToPay.toString() : ""));
            pendingToPay = pendingToPay.subtract(outStandingAmt);

            FieldProviderFactory.setField(data[i], "finSelectedCreditPaymentId",
                    "".equals(data[i].getField("paymentAmount")) ? "" : creditPayments.get(i).getId());
            FieldProviderFactory.setField(data[i], "rownum", String.valueOf(i));
        }
    } finally {
        OBContext.restorePreviousMode();
    }

    return data;
}

From source file:org.openbravo.erpCommon.ad_reports.MInOutTraceReports.java

private String insertTotal(String strTotal, String strUnit, String strTotalPedido, String strUnitPedido) {
    BigDecimal total, totalPedido;
    total = new BigDecimal(strTotal);
    totalPedido = (!strTotalPedido.equals("") ? new BigDecimal(strTotalPedido) : ZERO);
    total = total.setScale(2, BigDecimal.ROUND_HALF_UP);
    totalPedido = totalPedido.setScale(2, BigDecimal.ROUND_HALF_UP);
    StringBuffer resultado = new StringBuffer();
    resultado.append("<td class=\"DataGrid_Body_Cell_Amount\">\n");
    resultado.append(total.toString()).append(" ").append(strUnit);
    resultado.append("</td>\n");
    if (totalPedido.intValue() != 0) {
        resultado.append("<td class=\"DataGrid_Body_Cell_Amount\">\n");
        resultado.append(totalPedido.toString()).append(" ")
                .append(StringEscapeUtils.escapeHtml(strUnitPedido));
        resultado.append("</td>\n");
    }//from   w ww .j  a va2  s .com
    return resultado.toString();
}

From source file:com.cloudera.sqoop.tool.ImportTool.java

/**
 * Initialize the constraints which set the incremental import range.
 * @return false if an import is not necessary, because the dataset has not
 * changed.//from w w  w  .  j  a  v a  2s  .co  m
 */
private boolean initIncrementalConstraints(SqoopOptions options, ImportJobContext context)
        throws ImportException, IOException {

    // If this is an incremental import, determine the constraints
    // to inject in the WHERE clause or $CONDITIONS for a query.
    // Also modify the 'last value' field of the SqoopOptions to
    // specify the current job start time / start row.

    if (!isIncremental(options)) {
        return true;
    }

    SqoopOptions.IncrementalMode incrementalMode = options.getIncrementalMode();
    String nextIncrementalValue = null;

    switch (incrementalMode) {
    case AppendRows:
        try {
            BigDecimal nextVal = getMaxColumnId(options);
            if (null != nextVal) {
                nextIncrementalValue = nextVal.toString();
            }
        } catch (SQLException sqlE) {
            throw new IOException(sqlE);
        }
        break;
    case DateLastModified:
        Timestamp dbTimestamp = manager.getCurrentDbTimestamp();
        if (null == dbTimestamp) {
            throw new IOException("Could not get current time from database");
        }

        nextIncrementalValue = manager.timestampToQueryString(dbTimestamp);
        break;
    default:
        throw new ImportException("Undefined incremental import type: " + incrementalMode);
    }

    // Build the WHERE clause components that are used to import
    // only this incremental section.
    StringBuilder sb = new StringBuilder();
    String prevEndpoint = options.getIncrementalLastValue();

    if (incrementalMode == SqoopOptions.IncrementalMode.DateLastModified && null != prevEndpoint
            && !prevEndpoint.contains("\'")) {
        // Incremental imports based on timestamps should be 'quoted' in
        // ANSI SQL. If the user didn't specify single-quotes, put them
        // around, here.
        prevEndpoint = "'" + prevEndpoint + "'";
    }

    String checkColName = manager.escapeColName(options.getIncrementalTestColumn());
    LOG.info("Incremental import based on column " + checkColName);
    if (null != prevEndpoint) {
        if (prevEndpoint.equals(nextIncrementalValue)) {
            LOG.info("No new rows detected since last import.");
            return false;
        }
        LOG.info("Lower bound value: " + prevEndpoint);
        sb.append(checkColName);
        switch (incrementalMode) {
        case AppendRows:
            sb.append(" > ");
            break;
        case DateLastModified:
            sb.append(" >= ");
            break;
        default:
            throw new ImportException("Undefined comparison");
        }
        sb.append(prevEndpoint);
        sb.append(" AND ");
    }

    if (null != nextIncrementalValue) {
        sb.append(checkColName);
        switch (incrementalMode) {
        case AppendRows:
            sb.append(" <= ");
            break;
        case DateLastModified:
            sb.append(" < ");
            break;
        default:
            throw new ImportException("Undefined comparison");
        }
        sb.append(nextIncrementalValue);
    } else {
        sb.append(checkColName);
        sb.append(" IS NULL ");
    }

    LOG.info("Upper bound value: " + nextIncrementalValue);

    String prevWhereClause = options.getWhereClause();
    if (null != prevWhereClause) {
        sb.append(" AND (");
        sb.append(prevWhereClause);
        sb.append(")");
    }

    String newConstraints = sb.toString();
    options.setWhereClause(newConstraints);

    // Save this state for next time.
    SqoopOptions recordOptions = options.getParent();
    if (null == recordOptions) {
        recordOptions = options;
    }
    recordOptions.setIncrementalLastValue(nextIncrementalValue);

    return true;
}

From source file:com.rcv.ResultsWriter.java

private void generateSummarySpreadsheet(Map<Integer, Map<String, BigDecimal>> roundTallies, String precinct,
        String outputPath) throws IOException {
    String csvPath = outputPath + ".csv";
    Logger.log(Level.INFO, "Generating summary spreadsheets: %s...", csvPath);

    // Get all candidates sorted by their first round tally. This determines the display order.
    // container for firstRoundTally
    Map<String, BigDecimal> firstRoundTally = roundTallies.get(1);
    // candidates sorted by first round tally
    List<String> sortedCandidates = sortCandidatesByTally(firstRoundTally);

    // totalActiveVotesPerRound is a map of round to total votes cast in each round
    Map<Integer, BigDecimal> totalActiveVotesPerRound = new HashMap<>();
    // round indexes over all rounds plus final results round
    for (int round = 1; round <= numRounds; round++) {
        // tally is map of candidate to tally for the current round
        Map<String, BigDecimal> tallies = roundTallies.get(round);
        // total will contain total votes for all candidates in this round
        // this is used for calculating other derived data
        BigDecimal total = BigDecimal.ZERO;
        // tally indexes over all tallies for the current round
        for (BigDecimal tally : tallies.values()) {
            total = total.add(tally);/*from  ww  w .j ava2 s  .c  o  m*/
        }
        totalActiveVotesPerRound.put(round, total);
    }

    // csvPrinter will be used to write output to csv file
    CSVPrinter csvPrinter;
    try {
        BufferedWriter writer = Files.newBufferedWriter(Paths.get(csvPath));
        csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT);
    } catch (IOException exception) {
        Logger.log(Level.SEVERE, "Error creating CSV file: %s\n%s", csvPath, exception.toString());
        throw exception;
    }

    // print contest info
    addHeaderRows(csvPrinter, precinct);

    // add a row header for the round column labels
    csvPrinter.print("Rounds");
    // round indexes over all rounds
    for (int round = 1; round <= numRounds; round++) {
        // label string will have the actual text which goes in the cell
        String label = String.format("Round %d", round);
        // cell for round label
        csvPrinter.print(label);
    }
    csvPrinter.println();

    // actions don't make sense in individual precinct results
    if (precinct == null || precinct.isEmpty()) {
        addActionRows(csvPrinter);
    }

    final BigDecimal totalActiveVotesFirstRound = totalActiveVotesPerRound.get(1);

    // For each candidate: for each round: output total votes
    // candidate indexes over all candidates
    for (String candidate : sortedCandidates) {
        // show each candidate row with their totals for each round
        // text for the candidate name
        String candidateDisplayName = this.config.getNameForCandidateID(candidate);
        csvPrinter.print(candidateDisplayName);

        // round indexes over all rounds
        for (int round = 1; round <= numRounds; round++) {
            // vote tally this round
            BigDecimal thisRoundTally = roundTallies.get(round).get(candidate);
            // not all candidates may have a tally in every round
            if (thisRoundTally == null) {
                thisRoundTally = BigDecimal.ZERO;
            }
            // total votes cell
            csvPrinter.print(thisRoundTally.toString());
        }
        // advance to next line
        csvPrinter.println();
    }

    // row for the inactive CVR counts
    // inactive CVR header cell
    csvPrinter.print("Inactive ballots");

    // round indexes through all rounds
    for (int round = 1; round <= numRounds; round++) {
        // count of votes inactive this round
        BigDecimal thisRoundInactive = BigDecimal.ZERO;

        if (round > 1) {
            // Exhausted count is the difference between the total votes in round 1 and the total votes
            // in the current round.
            thisRoundInactive = totalActiveVotesFirstRound.subtract(totalActiveVotesPerRound.get(round))
                    .subtract(roundToResidualSurplus.get(round));
        }
        // total votes cell
        csvPrinter.print(thisRoundInactive.toString());
    }
    csvPrinter.println();

    // row for residual surplus (if needed)
    // We check if we accumulated any residual surplus over the course of the tabulation by testing
    // whether the value in the final round is positive.
    if (roundToResidualSurplus.get(numRounds).signum() == 1) {
        csvPrinter.print("Residual surplus");
        for (int round = 1; round <= numRounds; round++) {
            csvPrinter.print(roundToResidualSurplus.get(round).toString());
        }
        csvPrinter.println();
    }

    // write xls to disk
    try {
        // output stream is used to write data to disk
        csvPrinter.flush();
        csvPrinter.close();
    } catch (IOException exception) {
        Logger.log(Level.SEVERE, "Error saving file: %s\n%s", outputPath, exception.toString());
        throw exception;
    }
}

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccDb2LUW.CFAccDb2LUWSchema.java

public static String getUInt64String(BigDecimal val) {
    if (val == null) {
        return ("null");
    } else {/*  w  ww . j  a  v a2s . c o  m*/
        return (val.toString());
    }
}

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccDb2LUW.CFAccDb2LUWSchema.java

public static String getNumberString(BigDecimal val) {
    if (val == null) {
        return ("null");
    } else {//  www.  j  a  v a  2 s.  c om
        return (val.toString());
    }
}

From source file:org.apache.torque.oid.IDBroker.java

/**
 * Grabs more ids from the id_table and stores it in the ids
 * Hashtable.  If adjustQuantity is set to true the amount of id's
 * retrieved for each call to storeIDs will be adjusted.
 *
 * @param tableName The name of the table for which we want an id.
 * @param adjustQuantity True if amount should be adjusted.
 * @param connection a Connection//from w  w  w  . j a va2 s.  c  o m
 * @exception on a database error.
 */
private synchronized void storeIDs(String tableName, boolean adjustQuantity, Connection connection)
        throws TorqueException {
    log.debug("storeIDs(): Start retrieving ids from database.");
    BigDecimal nextId = null;
    BigDecimal quantity = null;

    // Block on the table.  Multiple tables are allowed to ask for
    // ids simultaneously.
    //        TableMap tMap = dbMap.getTable(tableName);
    //        synchronized(tMap)  see comment in the getNextIds method
    //        {
    if (adjustQuantity) {
        checkTiming(tableName);
    }

    boolean useNewConnection = (connection == null)
            || (configuration.getBoolean(DB_IDBROKER_USENEWCONNECTION, true));
    try {
        if (useNewConnection) {
            connection = Transaction.begin(databaseName);
            if (log.isTraceEnabled()) {
                log.trace("storeIDs(): fetched connection, " + "started transaction.");
            }
        }

        // Write the current value of quantity of keys to grab
        // to the database, primarily to obtain a write lock
        // on the table/row, but this value will also be used
        // as the starting value when an IDBroker is
        // instantiated.
        quantity = getQuantity(tableName, connection);
        updateQuantity(connection, tableName, quantity);

        // Read the next starting ID from the ID_TABLE.
        BigDecimal[] results = selectRow(connection, tableName);
        nextId = results[0]; // NEXT_ID column

        // Update the row based on the quantity in the
        // ID_TABLE.
        BigDecimal newNextId = nextId.add(quantity);
        updateNextId(connection, tableName, newNextId.toString());

        if (useNewConnection) {
            Transaction.commit(connection);
            if (log.isTraceEnabled()) {
                log.trace("storeIDs(): Transaction committed, " + "connection returned");
            }
        }
    } catch (TorqueException e) {
        if (useNewConnection) {
            Transaction.safeRollback(connection);
        }
        throw e;
    }

    List<BigDecimal> availableIds = ids.get(tableName);
    if (availableIds == null) {
        availableIds = new ArrayList<BigDecimal>();
        ids.put(tableName, availableIds);
    }

    // Create the ids and store them in the list of available ids.
    int numId = quantity.intValue();
    for (int i = 0; i < numId; i++) {
        availableIds.add(nextId);
        nextId = nextId.add(BigDecimal.ONE);
    }
    //        }
}

From source file:ru.tinkoff.acquiring.sdk.EnterCardFragment.java

private String getFormattedPrice() {
    Intent intent = getActivity().getIntent();
    Money money = (Money) intent.getSerializableExtra(PayFormActivity.EXTRA_AMOUNT);
    BigDecimal bigDecimal = new BigDecimal(money.getCoins());
    bigDecimal = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_EVEN);
    return bigDecimal.toString();
}

From source file:org.kuali.kpme.pm.position.web.PositionMaintainableServiceImpl.java

private boolean validateDutyListPercentage(PositionDutyBo pd, PositionBo aPosition) {
    if (CollectionUtils.isNotEmpty(aPosition.getDutyList()) && pd.getPercentage() != null) {
        BigDecimal sum = pd.getPercentage();
        for (PositionDutyBo aDuty : aPosition.getDutyList()) {
            if (aDuty != null && aDuty.getPercentage() != null) {
                sum = sum.add(aDuty.getPercentage());
            }/* w w  w  .  jav a2s  .co m*/
        }
        if (sum.compareTo(new BigDecimal(100)) > 0) {
            GlobalVariables.getMessageMap().putError(
                    "newCollectionLines['document.newMaintainableObject.dataObject.dutyList'].percentage",
                    "duty.percentage.exceedsMaximum", sum.toString());
            return false;
        }
    }
    return true;
}