List of usage examples for java.math BigDecimal valueOf
public static BigDecimal valueOf(double val)
From source file:com.aimluck.eip.project.ProjectTaskFormData.java
/** * ????/*w w w. j ava 2 s. c om*/ * * @param rundata * RunData * @param context * Context * @param msgList * * @return TRUE ? FALSE */ @Override protected boolean setFormData(RunData rundata, Context context, List<String> msgList) throws ALPageNotFoundException, ALDBErrorException { boolean res = super.setFormData(rundata, context, msgList); try { if (res) { String members[] = rundata.getParameters().getStrings("task_member"); String workload[] = rundata.getParameters().getStrings("workload"); if (members != null) { for (int i = 0; i < members.length; i++) { if (members[i] == null || members[i].length() == 0) { continue; } // ALEipUser user = ALEipUtils.getALEipUser(Integer.valueOf(members[i])); // BigDecimal w = BigDecimal.valueOf(0); try { if (workload[i] != null && workload[i].length() > 0) { w = new BigDecimal(workload[i]); } if (w.compareTo(BigDecimal.valueOf(0)) < 0) { msgList.add(getl10n("PROJECT_VALIDATE_WORKLOAD")); } else if (w.precision() - w.scale() > 5) { msgList.add(getl10n("PROJECT_VALIDATE_WORKLOAD_RATIONAL_INTEGER")); } else if (w.scale() > 3) { msgList.add(getl10n("PROJECT_VALIDATE_WORKLOAD_DECIMAL")); } } catch (Exception e) { msgList.add(getl10n("PROJECT_VALIDATE_WORKLOAD_INTEGER")); } ProjectTaskMemberResultData member = new ProjectTaskMemberResultData(); member.initField(); member.setUserId(user.getUserId().getValue()); member.setUserName(user.getAliasName().getValue()); member.setWorkload(w); taskMembers.add(member); } } planWorkloadString = rundata.getParameters().getString("plan_workload"); // fileuploadList = pfile.getFileuploadList(rundata); if (ALEipConstants.MODE_NEW_FORM.equals(getMode())) { String nullStr = null; start_date_check.setValue("TRUE"); start_date.setValue(nullStr); end_date_check.setValue("TRUE"); end_date.setValue(nullStr); } } } catch (RuntimeException ex) { logger.error("RuntimeException", ex); res = false; } catch (Exception ex) { logger.error("Exception", ex); res = false; } return res; }
From source file:pe.gob.mef.gescon.web.ui.LoginMB.java
public String ingresar() { String page = StringUtils.EMPTY; try {/*from ww w .j a va2s .c o m*/ if (StringUtils.isNotBlank(this.getLogin()) && StringUtils.isNotBlank(this.getPass())) { UserService service = (UserService) ServiceFinder.findBean("UserService"); User usuario = service.getUserByLogin(this.getLogin()); if (usuario != null) { PassService passService = (PassService) ServiceFinder.findBean("PassService"); Pass pas = passService.getPassByUser(usuario); if (pas != null && this.getPass().equals(pas.getVclave())) { ParametroService parametroService = (ParametroService) ServiceFinder .findBean("ParametroService"); Parametro passDefault = parametroService .getParametroById(BigDecimal.valueOf(Long.parseLong(Constante.CLAVE_DEFAULT))); if (pas.getVclave().equals(passDefault.getVvalor())) { ResourceBundle bundle = ResourceBundle.getBundle(Parameters.getMessages()); this.setNotificacion(bundle.getString("notificacion1")); this.setClaveDefault(true); this.setPass(StringUtils.EMPTY); this.setNewpass(StringUtils.EMPTY); this.setConfirmpass(StringUtils.EMPTY); RequestContext.getCurrentInstance().execute("PF('iniDialog').hide();"); RequestContext.getCurrentInstance().execute("PF('bar').show();"); RequestContext.getCurrentInstance().execute("PF('claDialog').show();"); return StringUtils.EMPTY; } Parametro caducidad = parametroService.getParametroById( BigDecimal.valueOf(Long.parseLong(Constante.DIAS_CADUCIDAD_CLAVE))); long dias = DateUtils.getDifferenceDays(pas.getDfechacreacion(), new Date()); if (dias > Long.parseLong(caducidad.getVvalor())) { ResourceBundle bundle = ResourceBundle.getBundle(Parameters.getMessages()); this.setNotificacion(bundle.getString("notificacion2")); this.setClaveCaducada(true); this.setPass(StringUtils.EMPTY); this.setNewpass(StringUtils.EMPTY); this.setConfirmpass(StringUtils.EMPTY); RequestContext.getCurrentInstance().execute("PF('iniDialog').hide();"); RequestContext.getCurrentInstance().execute("PF('bar').show();"); RequestContext.getCurrentInstance().execute("PF('claDialog').show();"); return StringUtils.EMPTY; } PerfilService perfilService = (PerfilService) ServiceFinder.findBean("PerfilService"); List<Perfil> listaperfiles = perfilService.getPerfilesByUser(usuario); if (!CollectionUtils.isEmpty(listaperfiles)) { this.setUser(usuario); this.setPerfil(listaperfiles.get(0)); PoliticaPerfilService politicaPerfilService = (PoliticaPerfilService) ServiceFinder .findBean("PoliticaPerfilService"); this.setPoliticas(politicaPerfilService .obtenerPoliticasByPerfil(this.getPerfil().getNperfilid())); AsignacionService asignacionService = (AsignacionService) ServiceFinder .findBean("AsignacionService"); this.setNotificaciones(asignacionService.getNumberNotificationsByUser(this.getUser())); this.setNotificacionesAsignadas( asignacionService.getNumberNotificationsAssignedByUser(this.getUser())); this.setNotificacionesRecibidas( asignacionService.getNumberNotificationsReceivedByUser(this.getUser())); this.setNotificacionesAtendidas( asignacionService.getNumberNotificationsServedByUser(this.getUser())); this.setNotificacionesPublicadas( asignacionService.getNumberNotificationsPublicByUser(this.getUser())); this.setListaNotificacionesAlerta( asignacionService.getNotificationsAlertPanelByMtuser(this.getUser())); if (this.getListaNotificacionesAlerta().isEmpty()) { this.setAlertaFlag("false"); } else { this.setAlertaFlag("true"); } if (this.getPerfil().getNperfilid().toString().equals(Constante.ROL_ADMINISTRADOR)) { page = "/pages/indexAdmin?faces-redirect=true"; } else { page = "/index?faces-redirect=true"; } } else { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, Constante.SEVERETY_ALERTA, "El usuario ingresado no cuenta con un rol asignado. \nComunquese con el administrador del servicio."); FacesContext.getCurrentInstance().addMessage(null, message); return StringUtils.EMPTY; } } else { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, Constante.SEVERETY_ALERTA, "La contrasea ingresada es incorrecta."); FacesContext.getCurrentInstance().addMessage(null, message); return StringUtils.EMPTY; } } else { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, Constante.SEVERETY_ALERTA, "El usuario ingresado no se encuentra registrado."); FacesContext.getCurrentInstance().addMessage(null, message); return StringUtils.EMPTY; } } else { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, Constante.SEVERETY_ALERTA, "Ingrese su usuario y contrasea para ingresar."); FacesContext.getCurrentInstance().addMessage(null, message); return StringUtils.EMPTY; } } catch (Exception e) { e.getMessage(); e.printStackTrace(); } return page; }
From source file:com.streamsets.pipeline.stage.it.DriftIT.java
@Test public void testChangedColumnTypeDecimal() throws Exception { executeUpdate("CREATE TABLE `decimal` (dec decimal(2, 1)) PARTITIONED BY (dt string) STORED AS AVRO"); HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder().table("decimal").decimalConfig(3, 2) .build();/*from w ww. j av a 2 s. c o m*/ HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build(); List<Record> records = new LinkedList<>(); Map<String, Field> map = new LinkedHashMap<>(); map.put("dec", Field.create(Field.Type.DECIMAL, BigDecimal.valueOf(2.2))); Record record = RecordCreator.create("s", "s:1"); record.set(Field.create(map)); records.add(record); try { processRecords(processor, hiveTarget, records); Assert.fail("Column type change haven't resulted in exception"); } catch (StageException e) { Assert.assertEquals(Errors.HIVE_21, e.getErrorCode()); Assert.assertTrue(e.getMessage().contains("Expected: DECIMAL(2,1), Actual: DECIMAL(3,2)")); } }
From source file:logic.EntityCar.java
private void estimate() { //BigDecimal pq = BigDecimal.valueOf(ie.params.size()); //BigDecimal pq = BigDecimal.valueOf(0); for (EntityPropertyHolder eph : aprops.values()) { //pq = pq.add(BigDecimal.valueOf(1)); dinamicRateA = dinamicRateA.add(eph.dinamicRate); //staticRate = staticRate.add(eph.staticRate); //suplog+="--"+eph.supLog+"--"; }/*from w ww . j a v a 2 s. c o m*/ for (EntityPropertyHolder eph : bprops.values()) { //pq = pq.add(BigDecimal.valueOf(1)); dinamicRateB = dinamicRateB.add(eph.dinamicRate); //staticRate = staticRate.add(eph.staticRate); //suplog += "=--" + eph.supLog + "--;"; if (!eph.activeProperty.isEmpty()) { suplog += eph.activeProperty.get(0).uid + "-" + eph.activeProperty.get(0).price + ";"; } } if (staticProps.keySet().size() > 0) { BigDecimal supsr = BigDecimal.valueOf(0); //BigDecimal divisor = BigDecimal.valueOf(staticProps.keySet().size()); for (String uid : staticProps.keySet()) { if (!staticProps.get(uid).isEmpty()) { supsr = supsr.add(staticProps.get(uid).get(0).value); } } staticRate = supsr; ///staticRate = supsr.divide(divisor, 2, RoundingMode.HALF_UP); } else { staticRate = BigDecimal.valueOf(0); } fullPrice = fullPrice.add(aFund2).add(bFund2); //suplog+="!stats: "+staticProps.keySet().size(); //staticRate = pq; //dinamicRate = dinamicRate.divide(pq,2, RoundingMode.HALF_UP); //staticRate = staticRate.divide(pq,2, RoundingMode.HALF_UP); }
From source file:com.ssbusy.controller.catalog.CategoryController.java
@RequestMapping({ "/catalog/products/page-back", "/catalog/products/page-forward" }) public String pageBack(@RequestParam("category-id") Long categoryId, @RequestParam("start") int start, @RequestParam("inner-category") String innerCategory, Model model) { model.addAttribute("catId", categoryId); model.addAttribute("start", BigDecimal.valueOf(start < 0 ? 0 : start)); model.addAttribute("type", innerCategory); return RETURN_PRODUCT_LIST_ITEM; }
From source file:jp.furplag.util.commons.NumberUtilsTest.java
/** * {@link jp.furplag.util.commons.NumberUtils#add(java.lang.Number, java.lang.Number)}. *//* ww w . j a v a 2s. co m*/ @SuppressWarnings("unchecked") @Test public void testAddTNumber() { assertEquals("null", null, add(null, null)); assertEquals("null", null, add(null, 10)); assertEquals("null", (Object) 123.456d, add(123.456, 0)); assertEquals("null", (Object) 123.456f, add(123.456f, 0)); assertEquals("123 + .456: Float", (Object) 123, add(123, .456f)); assertEquals("123 + .456: Float", (Object) Double.class, add(123d, .456f).getClass()); assertEquals("123 + .456: Float", (Object) BigDecimal.class, add(BigDecimal.valueOf(123d), .456f).getClass()); for (Class<?> type : NUMBERS) { try { Object o = null; Number augend = null; Class<? extends Number> typeOfN = (Class<? extends Number>) type; Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type); if (ClassUtils.isPrimitiveWrapper(wrapper)) { o = wrapper.getMethod("valueOf", String.class).invoke(null, "123"); } else { Constructor<?> c = type.getDeclaredConstructor(String.class); o = c.newInstance("123"); } assertEquals("123.456: " + type.getSimpleName(), add((Number) o, augend, typeOfN), add((Number) o, augend)); augend = .456f; assertEquals("123.456: " + type.getSimpleName(), add((Number) o, augend, typeOfN), add((Number) o, augend)); augend = Double.NaN; assertEquals("NaN: " + type.getSimpleName(), add((Number) o, augend, typeOfN), add((Number) o, augend)); augend = Float.NEGATIVE_INFINITY; assertEquals("-Infinity: Float: " + type.getSimpleName(), add((Number) o, augend, typeOfN), add((Number) o, augend)); augend = Double.POSITIVE_INFINITY; assertEquals("Infinity: Double: : " + type.getSimpleName(), add((Number) o, augend, typeOfN), add((Number) o, augend)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace())); } } }
From source file:com.examples.with.different.packagename.testcarver.NumberConverter.java
/** * Convert any Number object to the specified type for this * <i>Converter</i>.//from w ww.j a v a2 s. c om * <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) + "'"; throw new ConversionException(msg); }
From source file:com.ocs.dynamo.ui.composite.table.export.TableExportActionHandlerTest.java
private Table getTable() { BeanItemContainer<Person> container = new BeanItemContainer<>(Person.class); Person person1 = new Person(1, "Bas<br/>Bob", 35, BigDecimal.valueOf(76.0), BigDecimal.valueOf(12)); Person person2 = new Person(2, "Patrick", 44, BigDecimal.valueOf(77.0), BigDecimal.valueOf(15)); container.addAll(Lists.newArrayList(person1, person2)); return new ModelBasedTable<Integer, Person>(container, entityModelFactory.getModel(Person.class), entityModelFactory, messageService); }
From source file:churashima.action.manage.ExpensesAction.java
@Execute(validator = false) public String editExecute() { ExpensesDao expensesDao = SingletonS2Container.getComponent(ExpensesDao.class); Expenses expenses = expensesDao.selectById(Long.valueOf(expensesForm.expensesId)); SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); try {//from w w w .j av a2 s. co m expenses.date = sdf.parse(expensesForm.strDate); } catch (ParseException e) { e.printStackTrace(); } expenses.subjectId = expensesForm.subjectId; expenses.place = expensesForm.place; expenses.name = expensesForm.name; expenses.price = expensesForm.price; expenses.category = expensesForm.category; expenses.categoryDetail = expensesForm.detail; expenses.openFlg = expensesForm.openFlg; expenses.comment = expensesForm.comment; expenses.isExcludeTax = expensesForm.isExcludeTax; TaxDao taxDao = SingletonS2Container.getComponent(TaxDao.class); BigDecimal tax = taxDao.selectByDate(expenses.date); if (Const.TAX_EXCLUDE.equals(expensesForm.isExcludeTax)) { // ????? expenses.priceTax = expensesForm.price.multiply(tax); expenses.priceExcludeTax = expensesForm.price; expenses.price = expenses.priceExcludeTax.add(expenses.priceTax); } else { // ???? expenses.price = expensesForm.price; expenses.priceExcludeTax = expensesForm.price.divide(BigDecimal.valueOf(1).add(tax), 3, BigDecimal.ROUND_HALF_UP); // ? expenses.priceTax = expenses.price.subtract(expenses.priceExcludeTax); } expensesDao.update(expenses); if ("expensesList".equals(expensesForm.fromPageId)) { // ?????? return "search"; } else { // ?????? return "/manage/expenses"; } }
From source file:it.newfammulfin.api.EntryResource.java
private <K> boolean checkAndBalanceZeroShares(final Map<K, BigDecimal> shares, BigDecimal expectedSum) { if (shares.isEmpty()) { return false; }/*from w ww . jav a 2s . c om*/ boolean equalShares = false; if (!Util.containsNotZero(shares.values())) { equalShares = true; expectedSum = expectedSum.setScale(Math.max(DEFAULT_SHARE_SCALE, expectedSum.scale())); for (Map.Entry<K, BigDecimal> shareEntry : shares.entrySet()) { shareEntry.setValue(expectedSum.divide(BigDecimal.valueOf(shares.size()), RoundingMode.DOWN)); } } K largestKey = shares.keySet().iterator().next(); for (Map.Entry<K, BigDecimal> share : shares.entrySet()) { if (share.getValue().abs().compareTo(shares.get(largestKey).abs()) > 0) { largestKey = share.getKey(); } } BigDecimal remainder = Util.remainder(shares.values(), expectedSum); if (remainder.compareTo(BigDecimal.ZERO) != 0) { shares.put(largestKey, shares.get(largestKey).add(remainder)); } return equalShares; }