List of usage examples for java.math BigDecimal valueOf
public static BigDecimal valueOf(double val)
From source file:es.juntadeandalucia.panelGestion.negocio.vo.TaskVO.java
private void processCSVFile() throws Throwable { Table table = taskEntity.getTable(); Integer srid = Utils.getSRID(table.getEpsg()); String schemaTableName = TableUtils.getSchemaTable(table); BigDecimal totalSize = BigDecimal.valueOf(fileProcessor.getBytesLength()); int saveLine = 0; /* if the first line is not a header * then it is stored into the table/*w w w . ja v a 2 s . c o m*/ */ if (!firstLineHeader) { insertCSVHeader(schemaTableName, fileColumns, srid); } while (taskEntity.getState().getStatus() != Status.FINISHED) { insertCSVLine(schemaTableName, fileColumns, srid); updateCSVProgress(totalSize); // save the task state every 'LINES_TO_SAVE' lines processed if (saveLine == PanelSettings.taskLinesToSave) { saveTask(); saveLine = 0; } saveLine++; } }
From source file:net.sourceforge.fenixedu.presentationTier.docs.academicAdministrativeOffice.AdministrativeOfficeDocument.java
protected void addPriceFields() { final CertificateRequest certificateRequest = (CertificateRequest) getDocumentRequest(); final CertificateRequestPR certificateRequestPR = (CertificateRequestPR) getPostingRule(); final Money amountPerPage = certificateRequestPR.getAmountPerPage(); final Money baseAmountPlusAmountForUnits = certificateRequestPR.getBaseAmount().add(certificateRequestPR .getAmountPerUnit().multiply(BigDecimal.valueOf(certificateRequest.getNumberOfUnits()))); final Money urgencyAmount = certificateRequest.getUrgentRequest() ? certificateRequestPR.getBaseAmount() : Money.ZERO;/*from w w w .j av a2s . c o m*/ addParameter("printed", BundleUtil.getString(Bundle.ACADEMIC, getLocale(), "label.academicDocument.certificate.printingPriceLabel")); addParameter("printPriceLabel", BundleUtil.getString(Bundle.ACADEMIC, getLocale(), "label.academicDocument.certificate.issuingPriceLabel")); addParameter("urgency", BundleUtil.getString(Bundle.ACADEMIC, getLocale(), "label.academicDocument.certificate.fastDeliveryPriceLabel")); addParameter("total", BundleUtil.getString(Bundle.ACADEMIC, getLocale(), "label.academicDocument.certificate.totalsPriceLabel")); addParameter("amountPerPage", amountPerPage); addParameter("baseAmountPlusAmountForUnits", baseAmountPlusAmountForUnits); addParameter("urgencyAmount", urgencyAmount); addParameter("printPriceFields", printPriceParameters(certificateRequest)); }
From source file:com.liato.bankdroid.banking.banks.coop.Coop.java
@Override public void update() throws BankException, LoginException, BankChoiceException { super.update(); if (username == null || password == null || username.length() == 0 || password.length() == 0) { throw new LoginException(res.getText(R.string.invalid_username_password).toString()); }/* w ww.j a v a2 s .c om*/ login(); try { for (AccountType at : AccountType.values()) { response = urlopen.open(at.getUrl()); Document d = Jsoup.parse(response); Elements historik = d.select("#historik section"); TransactionParams params = new TransactionParams(); mTransactionParams.put(at, params); if (historik != null && !historik.isEmpty()) { String data = historik.first().attr("data-controller"); Matcher m = rePageGuid.matcher(data); if (m.find()) { params.setPageGuid(m.group(1)); } } Element date = d.getElementById("dateFrom"); if (date != null) { params.setMinDate(date.hasAttr("min") ? date.attr("min") : null); params.setMaxDate(date.hasAttr("max") ? date.attr("max") : null); } Elements es = d.select(".List:contains(Saldo)"); if (es != null && !es.isEmpty()) { List<String> names = new ArrayList<String>(); List<String> values = new ArrayList<String>(); for (Element e : es.first().select("dt")) { names.add(e.text().replaceAll(":", "").trim()); } for (Element e : es.first().select("dd")) { values.add(e.text().trim()); } for (int i = 0; i < Math.min(names.size(), values.size()); i++) { Account a = new Account(names.get(i), Helpers.parseBalance(values.get(i)), String.format("%s%d", at.getPrefix(), i)); a.setCurrency(Helpers.parseCurrency(values.get(i), "SEK")); if (a.getName().toLowerCase().contains("disponibelt")) { a.setType(Account.REGULAR); balance = a.getBalance(); setCurrency(a.getCurrency()); } else { a.setType(Account.OTHER); } if (i > 0) { a.setAliasfor(String.format("%s%d", at.getPrefix(), 0)); } accounts.add(a); } } } } catch (ClientProtocolException e) { e.printStackTrace(); throw new BankException(e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new BankException(e.getMessage()); } try { RefundSummaryRequest refsumReq = new RefundSummaryRequest(mUserId, mToken, APPLICATION_ID); HttpEntity e = new StringEntity(getObjectmapper().writeValueAsString(refsumReq)); InputStream is = urlopen .openStream("https://www.coop.se/ExternalServices/RefundService.svc/RefundSummary", e, true); RefundSummaryResponse refsumResp = readJsonValue(is, RefundSummaryResponse.class); if (refsumResp != null && refsumResp.getRefundSummaryResult() != null) { Account a = new Account("terbring p ditt kort", BigDecimal.valueOf(refsumResp.getRefundSummaryResult().getAccountBalance()), "refsummary"); a.setCurrency("SEK"); if (accounts.isEmpty()) { balance = a.getBalance(); setCurrency(a.getCurrency()); } accounts.add(a); a = new Account( String.format("terbring fr %s", refsumResp.getRefundSummaryResult().getMonthName()), BigDecimal.valueOf(refsumResp.getRefundSummaryResult().getTotalRefund()), "refsummary_month"); accounts.add(a); } } catch (JsonParseException e) { e.printStackTrace(); throw new BankException(e.getMessage()); } catch (ClientProtocolException e) { e.printStackTrace(); throw new BankException(e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new BankException(e.getMessage()); } if (accounts.isEmpty()) { throw new BankException(res.getText(R.string.no_accounts_found).toString()); } super.updateComplete(); }
From source file:de.hybris.platform.configurablebundleservices.bundle.impl.FindBundlePricingWithCurrentPriceFactoryStrategyTest.java
@Test public void testOneTimeChargePriceNoOneTimeChargeEntry() { given(childCart.getBillingTime()).willReturn(oneTimeChargeBillingEvent); given(priceRule.getBillingEvent()).willReturn(oneTimeChargeBillingEvent); given(priceRule.getPrice()).willReturn(BigDecimal.valueOf(RULE_HIGH_PRICE.doubleValue())); given(commercePriceService.getOneTimeChargeEntryPlan(pricePlan, oneTimeChargeBillingEvent)) .willReturn(null);//from w ww. j av a 2 s .co m given(oneTimeChargeEntry.getPrice()).willReturn(ONE_TIME_CHARGE_PLAN_PRICE); given(childEntry.getBasePrice()).willReturn(BASE_PRICE); given(oneTimeChargeEntry.getId()).willReturn("oneTimeChargeEntry"); given(priceRule.getId()).willReturn("priceRule"); final List<DiscountValue> discountValues = Lists.newArrayList(); bundlePriceFactory.reduceOneTimePrice(pricePlan, priceRule, discountValues, currency, childEntry); assertTrue(discountValues.isEmpty()); }
From source file:com.aegiswallet.utils.WalletUtils.java
public static String getBTCCurrencryValue(Context context, SharedPreferences prefs, BigDecimal amount) { String result = ""; File file = context.getApplicationContext().getFileStreamPath(Constants.BLOCKCHAIN_CURRENCY_FILE_NAME); if (file.exists()) { JSONObject jsonObject = BasicUtils.parseJSONData(context, Constants.BLOCKCHAIN_CURRENCY_FILE_NAME); try {//from w w w.j av a 2 s . c o m if (jsonObject != null) { JSONObject newObject = jsonObject .getJSONObject(prefs.getString(Constants.CURRENCY_PREF_KEY, null)); Double doubleVal = newObject.getDouble("last"); BigDecimal decimal = BigDecimal.valueOf(doubleVal); result = newObject.getString("symbol") + decimal.multiply(amount).setScale(2, RoundingMode.HALF_EVEN).toString(); } } catch (JSONException e) { Log.e("Wallet Utils", "JSON Exception " + e.getMessage()); } } return result; }
From source file:gpps.service.impl.ThirdPaySupportServiceImpl.java
@Override public Recharge getRecharge(String amount) throws LoginException { Recharge recharge = new Recharge(); recharge.setBaseUrl(innerThirdPaySupportService.getBaseUrl(IInnerThirdPaySupportService.ACTION_RECHARGE)); HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .getRequest();/*from ww w . ja v a 2 s .c o m*/ HttpSession session = req.getSession(); Object currentUser = session.getAttribute(ILoginService.SESSION_ATTRIBUTENAME_USER); if (currentUser == null) throw new LoginException("??"); recharge.setAmount(amount); recharge.setReturnURL(innerThirdPaySupportService.getReturnUrl() + "/account/recharge/response"); if ("1".equals(innerThirdPaySupportService.getAppendFlag())) recharge.setNotifyURL( innerThirdPaySupportService.getNotifyUrl() + "/account/recharge/response" + "/bg"); else recharge.setNotifyURL(innerThirdPaySupportService.getNotifyUrl()); recharge.setPlatformMoneymoremore(innerThirdPaySupportService.getPlatformMoneymoremore()); // recharge.setRechargeType("4"); // recharge.setFeeType("1"); // recharge.setSignInfo(recharge.getSign(innerThirdPaySupportService.getPrivateKey())); Integer cashStreamId = null; if (currentUser instanceof Lender) { Lender lender = (Lender) currentUser; recharge.setRechargeMoneymoremore(lender.getThirdPartyAccount()); cashStreamId = accountService.rechargeLenderAccount(lender.getAccountId(), BigDecimal.valueOf(Double.valueOf(amount)), ""); } else if (currentUser instanceof Borrower) { Borrower borrower = (Borrower) currentUser; recharge.setRechargeMoneymoremore(borrower.getThirdPartyAccount()); cashStreamId = accountService.rechargeBorrowerAccount(borrower.getAccountId(), BigDecimal.valueOf(Double.valueOf(amount)), ""); } else { throw new RuntimeException("??"); } recharge.setOrderNo(String.valueOf(cashStreamId)); recharge.setSignInfo(recharge.getSign(innerThirdPaySupportService.getPrivateKey())); return recharge; }
From source file:javadz.beanutils.converters.NumberConverter.java
/** * Convert any Number object to the specified type for this * <i>Converter</i>.//from w w w. j a va 2 s.com * <p> * This method handles conversion to the following types: * <ul> * <li><code>java.lang.Byte</code></li> * <li><code>java.lang.Short</code></li> * <li><code>java.lang.Integer</code></li> * <li><code>java.lang.Long</code></li> * <li><code>java.lang.Float</code></li> * <li><code>java.lang.Double</code></li> * <li><code>java.math.BigDecimal</code></li> * <li><code>java.math.BigInteger</code></li> * </ul> * @param sourceType The type being converted from * @param targetType The Number type to convert to * @param value The Number to convert. * * @return The converted value. */ private Number toNumber(Class sourceType, Class targetType, Number value) { // Correct Number type already if (targetType.equals(value.getClass())) { return value; } // Byte if (targetType.equals(Byte.class)) { long longValue = value.longValue(); if (longValue > Byte.MAX_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType)); } if (longValue < Byte.MIN_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too small " + toString(targetType)); } return new Byte(value.byteValue()); } // Short if (targetType.equals(Short.class)) { long longValue = value.longValue(); if (longValue > Short.MAX_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType)); } if (longValue < Short.MIN_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too small " + toString(targetType)); } return new Short(value.shortValue()); } // Integer if (targetType.equals(Integer.class)) { long longValue = value.longValue(); if (longValue > Integer.MAX_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType)); } if (longValue < Integer.MIN_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too small " + toString(targetType)); } return new Integer(value.intValue()); } // Long if (targetType.equals(Long.class)) { return new Long(value.longValue()); } // Float if (targetType.equals(Float.class)) { if (value.doubleValue() > Float.MAX_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType)); } return new Float(value.floatValue()); } // Double if (targetType.equals(Double.class)) { return new Double(value.doubleValue()); } // BigDecimal if (targetType.equals(BigDecimal.class)) { if (value instanceof Float || value instanceof Double) { return new BigDecimal(value.toString()); } else if (value instanceof BigInteger) { return new BigDecimal((BigInteger) value); } else { return BigDecimal.valueOf(value.longValue()); } } // BigInteger if (targetType.equals(BigInteger.class)) { if (value instanceof BigDecimal) { return ((BigDecimal) value).toBigInteger(); } else { return BigInteger.valueOf(value.longValue()); } } String msg = toString(getClass()) + " cannot handle conversion to '" + toString(targetType) + "'"; if (log().isWarnEnabled()) { log().warn(" " + msg); } throw new ConversionException(msg); }
From source file:com.ar.dev.tierra.api.controller.DetalleFacturaController.java
@RequestMapping(value = "/delete/discount", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> deleteDiscount(@RequestParam("dni") int dni, @RequestParam("password") String password, @RequestBody DetalleFactura detalleFactura) { Usuarios user = facadeService.getUsuariosDAO().findUsuarioByDNI(dni); boolean permiso = passwordEncoder.matches(password, user.getPassword()); if (permiso) { if (user.getRoles().getIdRol() == 1 || user.getRoles().getIdRol() == 6) { detalleFactura.setDescuentoDetalle(BigDecimal.ZERO); BigDecimal monto = detalleFactura.getProducto().getPrecioVenta() .multiply(BigDecimal.valueOf(detalleFactura.getCantidadDetalle())); detalleFactura.setTotalDetalle(monto); facadeService.getDetalleFacturaDAO().update(detalleFactura); List<DetalleFactura> detallesFactura = facadeService.getDetalleFacturaDAO() .facturaDetalle(detalleFactura.getFactura().getIdFactura()); BigDecimal sumMonto = new BigDecimal(BigInteger.ZERO); Factura factura = facadeService.getFacturaDAO() .searchById(detalleFactura.getFactura().getIdFactura()); for (DetalleFactura detailList : detallesFactura) { sumMonto = sumMonto.add(detailList.getTotalDetalle()); }// www . j av a 2 s. com factura.setTotal(sumMonto); factura.setFechaModificacion(new Date()); factura.setUsuarioModificacion(user.getIdUsuario()); facadeService.getFacturaDAO().update(factura); JsonResponse msg = new JsonResponse("Success", "Descuento eliminado con exito."); return new ResponseEntity<>(msg, HttpStatus.OK); } else { JsonResponse msg = new JsonResponse("Error", "No tienes los permisos necesarios para realizar esta operacion."); return new ResponseEntity<>(msg, HttpStatus.BAD_REQUEST); } } else { JsonResponse msg = new JsonResponse("Error", "No tienes los permisos necesarios para realizar esta operacion."); return new ResponseEntity<>(msg, HttpStatus.BAD_REQUEST); } }
From source file:com.greatmancode.craftconomy3.Common.java
/** * Format a balance to a readable string. * * @param worldName The world Name associated with this balance * @param currency The currency instance associated with this balance. * @param balance The balance.//from w ww. j av a 2 s . co m * @param format the display format to use * @return A pretty String showing the balance. Returns a empty string if currency is invalid. */ public String format(String worldName, Currency currency, double balance, DisplayFormat format) { StringBuilder string = new StringBuilder(); if (worldName != null && !worldName.equals(WorldGroupsManager.DEFAULT_GROUP_NAME)) { // We put the world name if the conf is true string.append(worldName).append(": "); } if (currency != null) { // We removes some cents if it's something like 20.20381 it would set it // to 20.20 String[] theAmount = BigDecimal.valueOf(balance).toPlainString().split("\\."); DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(); unusualSymbols.setGroupingSeparator(','); DecimalFormat decimalFormat = new DecimalFormat("###,###", unusualSymbols); String name = currency.getName(); if (balance > 1.0 || balance < 1.0) { name = currency.getPlural(); } String coin; if (theAmount.length == 2) { if (theAmount[1].length() >= 2) { coin = theAmount[1].substring(0, 2); } else { coin = theAmount[1] + "0"; } } else { coin = "0"; } String amount; try { amount = decimalFormat.format(Double.parseDouble(theAmount[0])); } catch (NumberFormatException e) { amount = theAmount[0]; } // Do we seperate money and dollar or not? if (format == DisplayFormat.LONG) { String subName = currency.getMinor(); if (Long.parseLong(coin) > 1) { subName = currency.getMinorPlural(); } string.append(amount).append(" ").append(name).append(" ").append(coin).append(" ").append(subName); } else if (format == DisplayFormat.SMALL) { string.append(amount).append(".").append(coin).append(" ").append(name); } else if (format == DisplayFormat.SIGN) { string.append(currency.getSign()).append(amount).append(".").append(coin); } else if (format == DisplayFormat.MAJORONLY) { string.append(amount).append(" ").append(name); } } return string.toString(); }
From source file:com.ocs.dynamo.ui.composite.table.export.TableExportActionHandlerTest.java
private TreeTable getTreeTable() { // BeanItemContainer<Person> container = new // BeanItemContainer<>(Person.class); final Person person1 = new Person(1, "Bas<br/>Bob", 35, BigDecimal.valueOf(76.0), BigDecimal.valueOf(12)); final Person person2 = new Person(2, "Patrick", 44, BigDecimal.valueOf(77.0), BigDecimal.valueOf(15)); // container.addAll(Lists.newArrayList(person1, person2)); final Department department = new Department(); department.setName("Special ops"); department.setEmployees(Sets.newHashSet(person1, person2)); CustomTreeTable<Integer, Person, Integer, Department> table = new CustomTreeTable<Integer, Person, Integer, Department>() { private static final long serialVersionUID = -6428315820101615753L; @Override/*from w w w. java 2 s . com*/ protected boolean isRightAligned(String propertyId) { return false; } @Override protected boolean isEditable(String propertyId) { return false; } @Override protected Number handleChange(String propertyId, String rowId, String parentRowId, String childKey, String parentKey, Object newValue) { return 0; } @Override protected String[] getSumColumns() { return new String[0]; } @Override protected List<Person> getRowCollection(Department dep) { return Lists.newArrayList(person1, person2); } @Override protected String getReportTitle() { return "Departments"; } @Override protected String getPreviousColumnId(String columnId) { return null; } @Override protected List<Department> getParentCollection() { return Lists.newArrayList(department); } @Override protected String getKeyPropertyId() { return "name"; } @Override protected String[] getColumnstoUpdate(String propertyId) { return new String[0]; } @Override protected void fillParentRow(Object[] row, Department entity) { // do nothing row[0] = entity.getName(); } @Override protected void fillChildRow(Object[] row, Person entity, Department parentEntity) { row[0] = entity.getName(); row[1] = entity.getAge(); } @Override protected void addContainerProperties() { addContainerProperty("name", String.class, null); addContainerProperty("age", Integer.class, null); } @Override protected Class<?> getEditablePropertyClass(String propertyId) { return Integer.class; } }; table.build(); return table; }