List of usage examples for java.math BigDecimal toPlainString
public String toPlainString()
From source file:op.tools.SYSTools.java
public static String getAsHTML(BigDecimal bd) { String dbl = bd.toPlainString(); if (dbl.endsWith(".00")) { dbl = dbl.substring(0, dbl.length() - 3); } else if (dbl.equals("0.50")) { dbl = "½"; } else if (dbl.equals("0.25")) { dbl = "¼"; } else if (dbl.equals("0.75")) { dbl = "¾"; } else if (dbl.equals("0.33")) { dbl = "<sup>1</sup>/<sub>3</sub>"; }//from w w w. j ava 2 s .c om return dbl; }
From source file:org.dash.wallet.integration.uphold.ui.UpholdWithdrawalDialog.java
private void transfer(BigDecimal value, final boolean deductFeeFromAmount) { final ProgressDialog progressDialog = showLoading(); UpholdClient.getInstance().createDashWithdrawalTransaction(value.toPlainString(), receivingAddress, new UpholdClient.Callback<UpholdTransaction>() { @Override//from ww w. j a va 2s.c o m public void onSuccess(UpholdTransaction tx) { transaction = tx; progressDialog.dismiss(); showCommitTransactionConfirmationDialog(deductFeeFromAmount); } @Override public void onError(Exception e, boolean otpRequired) { progressDialog.dismiss(); if (otpRequired) { showOtpDialog(); } else { showLoadingError(); } } }); }
From source file:uk.dsxt.voting.common.cryptoVote.CryptoVoteAcceptorWeb.java
@Override public NodeVoteReceipt acceptVote(String transactionId, String votingId, BigDecimal packetSize, String clientId, BigDecimal clientPacketResidual, String encryptedData, String voteDigest, String clientSignature) { Map<String, String> parameters = new HashMap<>(); parameters.put("transactionId", transactionId); parameters.put("votingId", votingId); parameters.put("packetSize", packetSize.toPlainString()); parameters.put("clientId", clientId); parameters.put("clientPacketResidual", clientPacketResidual.toPlainString()); parameters.put("encryptedData", encryptedData); parameters.put("voteDigest", voteDigest); parameters.put("clientSignature", clientSignature); unsentVoteMessages.add(parameters);/*from ww w. jav a 2 s. c o m*/ return null; }
From source file:com.stratio.cassandra.lucene.schema.mapping.BigDecimalMapper.java
/** {@inheritDoc} */ @Override/* ww w . java 2 s . com*/ protected String doBase(String name, Object value) { // Parse big decimal BigDecimal bd; try { bd = new BigDecimal(value.toString()); } catch (NumberFormatException e) { throw new IndexException("Field '%s' requires a base 10 decimal, but found '%s'", name, value); } // Split integer and decimal part bd = bd.stripTrailingZeros(); String[] parts = bd.toPlainString().split("\\."); validateIntegerPart(name, value, parts); validateDecimalPart(name, value, parts); BigDecimal complemented = bd.add(complement); String bds[] = complemented.toString().split("\\."); String integerPart = StringUtils.leftPad(bds[0], integerDigits + 1, '0'); String decimalPart = bds.length == 2 ? bds[1] : "0"; return integerPart + "." + decimalPart; }
From source file:org.openbravo.advpaymentmngt.filterexpression.AddPaymentDefaultValuesHandler.java
/** * Generated Credit default value//from w w w. j a v a 2 s .c o m * * @param requestMap * map with parameters */ public String getDefaultGeneratedCredit(Map<String, String> requestMap) throws JSONException { BigDecimal generateCredit = BigDecimal.ZERO; return generateCredit.toPlainString(); }
From source file:org.jvnet.hudson.plugins.backup.utils.BackupTask.java
public void run() { assert (logFilePath != null); assert (configuration.getFileNameTemplate() != null); SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM); startDate = new Date(); try {// w w w .ja v a 2 s. co m logger = new BackupLogger(logFilePath, configuration.isVerbose()); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Unable to open log file for writing: {0}", logFilePath); return; } logger.info("Backup started at " + getTimestamp(startDate)); // Have to include shutdown time in backup time ? waitNoJobsInQueue(); // file filter specific to what's inside jobs' worskpace IOFileFilter jobsExclusionFileFilter = null; // Creating global exclusions List<String> exclusions = new ArrayList<String>(); exclusions.addAll(Arrays.asList(DEFAULT_EXCLUSIONS)); exclusions.addAll(configuration.getCustomExclusions()); if (!configuration.getKeepWorkspaces()) { exclusions.add(WORKSPACE_NAME); } else { jobsExclusionFileFilter = createJobsExclusionFileFilter(hudsonWorkDir, configuration.getJobIncludes(), configuration.getJobExcludes(), configuration.getCaseSensitive()); } if (!configuration.getKeepFingerprints()) { exclusions.add(FINGERPRINTS_NAME); } if (!configuration.getKeepBuilds()) { exclusions.add(BUILDS_NAME); } if (!configuration.getKeepArchives()) { exclusions.add(ARCHIVE_NAME); } IOFileFilter filter = createFileFilter(exclusions, jobsExclusionFileFilter); try { BackupEngine backupEngine = new BackupEngine(logger, hudsonWorkDir, backupFileName, configuration.getArchiveType().getArchiver(), filter); backupEngine.doBackup(); } catch (BackupException e) { e.printStackTrace(logger.getWriter()); } finally { cancelNoJobs(); endDate = new Date(); logger.info("Backup end at " + getTimestamp(endDate)); BigDecimal delay = new BigDecimal(endDate.getTime() - startDate.getTime()); delay = delay.setScale(2, BigDecimal.ROUND_HALF_UP); delay = delay.divide(new BigDecimal("1000")); logger.info("[" + delay.toPlainString() + "s]"); finished = true; logger.close(); } }
From source file:com.tesora.dve.mysqlapi.repl.messages.MyUserVarLogEvent.java
String processDecimalValue(ByteBuf cb, int valueLen) throws PEException { String value = StringUtils.EMPTY; byte precision = cb.readByte(); byte scale = cb.readByte(); int intg = (int) precision - (int) scale; int intg0 = intg / DIG_PER_DEC1; int frac0 = (int) scale / DIG_PER_DEC1; int intg0x = intg - intg0 * DIG_PER_DEC1; int frac0x = (int) scale - frac0 * DIG_PER_DEC1; int firstValue = intg0 * 4 + dig2bytes[intg0x]; int secondValue = frac0 * 4 + dig2bytes[frac0x]; int binSize = firstValue + secondValue; int readableBytes = cb.readableBytes(); if ((firstValue < 1 && secondValue < 1) || readableBytes < binSize) { throw new PEException("Cannot decode binary decimal"); }//from ww w.j a va 2 s .co m ByteBuf chunk = PooledByteBufAllocator.DEFAULT.heapBuffer(binSize); cb.readBytes(chunk); // 1st byte is special cause it determines the sign byte firstByte = chunk.getByte(0); int sign = (firstByte & 0x80) == 0x80 ? 1 : -1; // invert sign chunk.setByte(0, (firstByte ^ 0x80)); if (sign == -1) { // invert all the bytes for (int i = 0; i < binSize; i++) { chunk.setByte(i, ~chunk.getByte(i)); } } BigDecimal integerPortion = decodeBinDecimal(chunk, firstValue, true); BigDecimal fractionPortion = decodeBinDecimal(chunk, secondValue, false); value = ((sign == -1) ? "-" : StringUtils.EMPTY) + integerPortion.toPlainString() + "." + fractionPortion.toPlainString(); return value; }
From source file:com.streamsets.pipeline.lib.salesforce.SobjectRecordCreator.java
protected String fixOffset(String offsetColumn, String offset) { com.sforce.soap.partner.Field sfdcField = getFieldMetadata(sobjectType, offsetColumn); if (SobjectRecordCreator.DECIMAL_TYPES.contains(sfdcField.getType().toString()) && offset.contains("E")) { BigDecimal val = new BigDecimal(offset); offset = val.toPlainString(); if (val.compareTo(MAX_OFFSET_INT) > 0 && !offset.contains(".")) { // We need the ".0" suffix since Salesforce doesn't like integer // bigger than 2147483647 offset += ".0"; }// w w w. ja v a 2s. c o m } return offset; }
From source file:com.google.enterprise.connector.salesforce.storetype.DBStore.java
public void setDocList(String checkpoint, String str_store_entry) { DatabaseMetaData dbm = null;//from w ww . j a va2s . c o m Connection connection = null; logger.log(Level.FINEST, "Setting doclist " + checkpoint); logger.log(Level.FINEST, "Setting store_entry " + str_store_entry); try { connection = ds.getConnection(); connection.setAutoCommit(true); dbm = connection.getMetaData(); //logger.log(Level.FINE,"Base64 ENCODING..."); String encode_entry = new String( org.apache.commons.codec.binary.Base64.encodeBase64(str_store_entry.getBytes())); str_store_entry = encode_entry; //logger.log(Level.FINE,"Setting store_entry ENCODED " + str_store_entry); if (dbm.getDatabaseProductName().equals("MySQL")) { //get the most recent row Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); String update_stmt = "select crawl_set from " + this.instance_table + " where crawl_set=(select max(crawl_set) from " + this.instance_table + ")"; logger.log(Level.FINE, "Getting lastentryp in db: " + update_stmt); ResultSet rs = statement.executeQuery(update_stmt); boolean ret_rows = rs.first(); String last_entry_in_db = null; while (ret_rows) { BigDecimal crawl_set = rs.getBigDecimal("crawl_set"); last_entry_in_db = crawl_set.toPlainString(); ret_rows = rs.next(); } logger.log(Level.FINER, "Last_Entry_in_Database " + last_entry_in_db); if (last_entry_in_db != null) { if (last_entry_in_db.startsWith(checkpoint)) { //increment if in the same set BigDecimal bd = new BigDecimal(last_entry_in_db); bd = bd.add(new BigDecimal(".00001")); logger.log(Level.INFO, "Adding to DBStore. Index Value: " + bd.toPlainString()); update_stmt = "insert into " + this.instance_table + " (crawl_set,crawl_data) values (?,COMPRESS(?))"; PreparedStatement ps = connection.prepareStatement(update_stmt); ps.setString(1, bd.toPlainString()); ps.setString(2, str_store_entry); ps.executeUpdate(); ps.close(); } else { //otherwise add the the 0th row for this set logger.log(Level.INFO, "Adding to DBStore. Index Value: " + checkpoint + ".00000"); update_stmt = "insert into " + this.instance_table + " (crawl_set,crawl_data) values (?,COMPRESS(?))"; PreparedStatement ps = connection.prepareStatement(update_stmt); ps.setString(1, checkpoint + ".00000"); ps.setString(2, str_store_entry); ps.executeUpdate(); ps.close(); } } else { logger.log(Level.INFO, "Adding to DBStore. Index Value: " + checkpoint + ".00000"); update_stmt = "insert into " + this.instance_table + " (crawl_set,crawl_data) values (?,COMPRESS(?))"; PreparedStatement ps = connection.prepareStatement(update_stmt); ps.setString(1, checkpoint + ".00000"); ps.setString(2, str_store_entry); ps.executeUpdate(); ps.close(); } rs.close(); statement.close(); connection.close(); } } catch (Exception ex) { logger.log(Level.SEVERE, "Exception initializing context Datasource " + ex); return; } }
From source file:org.yes.cart.payment.impl.PayPalButtonPaymentGatewayImpl.java
/** * {@inheritDoc}/*from ww w. j a v a 2 s.co m*/ */ public String getHtmlForm(final String cardHolderName, final String locale, final BigDecimal amount, final String currencyCode, final String orderReference, final Payment payment) { final StringBuilder form = new StringBuilder(); form.append(getHiddenFieldValue("button", "buynow")); form.append(getHiddenFieldValue("cmd", "_cart")); form.append(getHiddenFieldValue("upload", "1")); form.append(getHiddenFieldValue("paymentaction", "sale")); form.append(getHiddenFieldParam("business", PPB_USER)); form.append(getHiddenFieldParam("env", PPB_ENVIRONMENT)); form.append(getHiddenFieldParam("notify_url", PPB_NOTIFYURL)); form.append(getHiddenFieldParam("return", PPB_RETURNURL)); form.append(getHiddenFieldParam("cancel_return", PPB_CANCELURL)); form.append(getHiddenFieldValue("currency_code", currencyCode)); form.append(getHiddenFieldValue("invoice", orderReference)); form.append(getHiddenFieldValue("custom", orderReference)); form.append(getHiddenFieldValue("lc", paymentLocaleTranslator.translateLocale(this, locale))); form.append(getHiddenFieldValue("charset", "UTF-8")); if (payment.getBillingAddress() != null) { form.append(getHiddenFieldValue("first_name", payment.getBillingAddress().getFirstname())); form.append(getHiddenFieldValue("last_name", payment.getBillingAddress().getLastname())); form.append(getHiddenFieldValue("email", payment.getBillingEmail())); } if (payment.getShippingAddress() != null) { form.append(getHiddenFieldValue("address1", payment.getShippingAddress().getAddrline1())); form.append(getHiddenFieldValue("address2", payment.getShippingAddress().getAddrline2())); form.append(getHiddenFieldValue("city", payment.getShippingAddress().getCity())); form.append(getHiddenFieldValue("country", payment.getShippingAddress().getCountryCode())); form.append(getHiddenFieldValue("state", payment.getShippingAddress().getStateCode())); form.append(getHiddenFieldValue("zip", payment.getShippingAddress().getPostcode())); form.append(getHiddenFieldValue("address_override", "1")); } BigDecimal totalItems = Total.ZERO; int i = 1; for (final PaymentLine item : payment.getOrderItems()) { form.append(getHiddenFieldValue("item_name_" + i, item.getSkuName())); form.append(getHiddenFieldValue("item_number_" + i, item.getSkuCode())); // PayPal can only handle whole values, so do ceil final BigDecimal ppQty = item.getQuantity().setScale(0, BigDecimal.ROUND_CEILING); form.append(getHiddenFieldValue("quantity_" + i, ppQty.toPlainString())); final BigDecimal taxUnit = MoneyUtils.isFirstBiggerThanSecond(item.getTaxAmount(), Total.ZERO) ? item.getTaxAmount().divide(item.getQuantity(), Total.ZERO.scale(), RoundingMode.HALF_UP) : Total.ZERO; final BigDecimal itemAmount = item.getUnitPrice().subtract(taxUnit); form.append(getHiddenFieldValue("amount_" + i, itemAmount.toPlainString())); // form.append(getHiddenFieldValue("tax_" + i, taxUnit.setScale(Total.ZERO.scale(), RoundingMode.HALF_UP).toPlainString())); if (ppQty.compareTo(item.getQuantity()) != 0) { // If we have decimals in qty need to save it as item option form.append(getHiddenFieldValue("on0_" + i, "x")); form.append(getHiddenFieldValue("on1_" + i, item.getQuantity().toPlainString())); } i++; totalItems = totalItems.add(itemAmount.multiply(item.getQuantity())); } final BigDecimal payNet = payment.getPaymentAmount().subtract(payment.getTaxAmount()); if (payNet.compareTo(totalItems) < 0) { form.append(getHiddenFieldValue("discount_amount_cart", totalItems.subtract(payNet) .setScale(Total.ZERO.scale(), RoundingMode.HALF_UP).toPlainString())); } form.append(getHiddenFieldValue("tax_cart", payment.getTaxAmount().toPlainString())); return form.toString(); }