Example usage for java.text DecimalFormat setParseBigDecimal

List of usage examples for java.text DecimalFormat setParseBigDecimal

Introduction

In this page you can find the example usage for java.text DecimalFormat setParseBigDecimal.

Prototype

public void setParseBigDecimal(boolean newValue) 

Source Link

Document

Sets whether the #parse(java.lang.String,java.text.ParsePosition) method returns BigDecimal .

Usage

From source file:org.efaps.esjp.assets.LifecycleCostAbstract_Base.java

protected DecimalFormat getFormatInstance() throws EFapsException {
    final DecimalFormat ret = (DecimalFormat) NumberFormat.getInstance(Context.getThreadContext().getLocale());
    ret.setParseBigDecimal(true);
    return ret;/*from  ww  w  . j  ava 2 s  . com*/
}

From source file:org.opensingular.form.wicket.mapper.MoneyMapper.java

private String formatDecimal(BigDecimal bigDecimal, Integer casasDecimais) {
    DecimalFormat nf = (DecimalFormat) DecimalFormat.getInstance(new Locale("pt", "BR"));
    nf.setParseBigDecimal(true);
    nf.setGroupingUsed(true);//w w w. j a v a2  s.  c  o  m
    nf.setMinimumFractionDigits(casasDecimais);
    nf.setMaximumFractionDigits(casasDecimais);
    return nf.format(bigDecimal);
}

From source file:br.com.webbudget.domain.misc.filter.MovementFilter.java

/**
 * Metodo para fazer o parse da nossa criteria em um numero decimal para
 * satisfazer a busca por valor/*from w  w w .java 2  s . co m*/
 *
 * @return o valor formatador em bigdecimal
 *
 * @throws ParseException se houver algum erro na hora do parse
 */
public BigDecimal criteriaToBigDecimal() throws ParseException {

    final DecimalFormatSymbols symbols = new DecimalFormatSymbols();

    symbols.setGroupingSeparator('.');
    symbols.setDecimalSeparator(',');

    DecimalFormat decimalFormat = new DecimalFormat("#,##0.0#", symbols);
    decimalFormat.setParseBigDecimal(true);

    return (BigDecimal) decimalFormat.parse(this.criteria);
}

From source file:CommonServlets.EditUser.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String email = null, userName = null, job = null, address = null, password = null, img = null, role = null;
    BigDecimal creditLimit = new BigDecimal(0);

    try {/* w  w w  . j  av a 2s.co  m*/
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {
                //processFormField(item);
                String name = item.getFieldName();
                String value = item.getString();

                if (name.equalsIgnoreCase("email")) {
                    email = value;
                } else if (name.equalsIgnoreCase("userName")) {
                    userName = value;
                } else if (name.equalsIgnoreCase("creditLimit")) {
                    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
                    symbols.setGroupingSeparator(',');
                    symbols.setDecimalSeparator('.');
                    String pattern = "#,##0.0#";
                    DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
                    decimalFormat.setParseBigDecimal(true);
                    creditLimit = (BigDecimal) decimalFormat.parse(value);
                } else if (name.equalsIgnoreCase("job")) {
                    job = value;

                } else if (name.equalsIgnoreCase("address")) {
                    address = value;
                } else if (name.equalsIgnoreCase("password")) {
                    password = value;
                }
            } else if (!item.isFormField() && !item.getName().equals("")) {
                System.out.println(new File(AddProduct.class.getClassLoader().getResource("").getPath()
                        .replace("%20", " ")
                        .substring(0, AddProduct.class.getClassLoader().getResource("").getPath()
                                .replace("%20", " ").length() - 27)
                        + "/web/Resources/users_pics/" + item.getName()));
                item.write(new File(AddProduct.class.getClassLoader().getResource("").getPath()
                        .replace("%20", " ")
                        .substring(0, AddProduct.class.getClassLoader().getResource("").getPath()
                                .replace("%20", " ").length() - 27)
                        + "/web/Resources/users_pics/" + item.getName()));
                img = item.getName();
            }
        }

        User u = new User(email, userName, password, creditLimit, job, address, img, role);
        controlServlet.editUserDate(u);
        HttpSession session = request.getSession(true);
        session.setAttribute("done", "1");
        ControlServlet c = new ControlServlet();
        User myUser = c.getUser(userName);
        session.setAttribute("user", myUser);
        response.sendRedirect("UserHome.jsp");

    } catch (Exception ex) {
        Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:de.hybris.platform.acceleratorservices.payment.cybersource.strategies.impl.DefaultCreateSubscriptionRequestStrategy.java

/**
 * Gets the CyberSource setup fee, currently populated by a config value.
 * //w ww .  j  a  v  a 2  s .co  m
 * @return the CyberSource setup fee amount
 */
protected BigDecimal getSetupFeeAmount() {
    final String configSetupFee = getSiteConfigProperty(CyberSourceConstants.HopProperties.HOP_SETUP_FEE);
    if (configSetupFee != null && !configSetupFee.isEmpty()) {
        try {
            final DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance();
            formatter.setParseBigDecimal(true);
            return (BigDecimal) formatter.parse(configSetupFee);
        } catch (final Exception e) {
            LOG.debug("Error converting to BigDecimal of String value: " + configSetupFee, e);
        }
    }
    return null;
}

From source file:no.abmu.questionnaire.domain.data.BigDecimalFieldData.java

@Transient
private DecimalFormat getNumberFormat() {
    Locale locale = LocaleTypeNameConst.BOKMAAL;
    DecimalFormat numberFormat = (DecimalFormat) DecimalFormat.getInstance(locale);
    numberFormat.setMinimumFractionDigits(bigDecimalScale);
    numberFormat.setParseBigDecimal(true);
    return numberFormat;
}

From source file:de.betterform.xml.xforms.ui.AbstractFormControl.java

private BigDecimal strictParse(String value, Locale locale) throws ParseException {
    DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(locale);
    format.setParseBigDecimal(true);
    value = value.trim();//from   w ww .j  a v a  2s  .com
    ParsePosition pos = new ParsePosition(0);
    BigDecimal number = (BigDecimal) format.parse(value, pos);
    boolean okay = pos.getIndex() == value.length() && pos.getErrorIndex() == -1;
    if (!okay)
        throw new ParseException("Could not parse '" + value + "' as a number", pos.getErrorIndex());
    return number;
}

From source file:org.jbpm.formModeler.core.processing.fieldHandlers.NumericFieldHandler.java

/**
 * Builds a correct paramValue for a given inputValue.
 *
 * @param value   Object value to build its paramValue
 * @param pattern pattern to apply if any
 * @return a String[] with the paramValue on it or null if the value received is null
 *//*from  www. j a v a 2  s  .  com*/
protected String[] buildParamValue(Object value, String pattern) {
    String[] result = null;
    if (value != null && Arrays.asList(getCompatibleClassNames()).contains(value.getClass().getName())) {
        if (pattern != null && !"".equals(pattern)) { // Float and Double fields type always have pattern
            try {
                DecimalFormat df = (DecimalFormat) DecimalFormat
                        .getInstance(new Locale(LocaleManager.currentLang()));
                if (value instanceof BigDecimal)
                    df.setParseBigDecimal(true);
                df.applyPattern(pattern);

                if (value instanceof Float) {
                    value = df.format((((Float) value).floatValue()));
                } else if (value instanceof BigDecimal) {
                    value = df.format(value);
                } else {
                    value = df.format((((Double) value)).doubleValue());
                }
            } catch (Exception e) {
                if (value instanceof Short || value instanceof Integer || value instanceof Long
                        || value instanceof BigInteger) {
                    return buildParamValue(value, null);
                }
                return result;
            }
        }
        result = new String[] { value.toString() };
    }
    return result;
}

From source file:org.efaps.esjp.accounting.util.data.ConSis.java

protected List<Account> readAccounts4SaldoConcar(final File _file) throws IOException, ParseException {
    final List<Account> ret = new ArrayList<>();
    final BufferedReader in = new BufferedReader(new FileReader(_file));
    final CSVReader reader = new CSVReader(in);
    final List<String[]> rows = reader.readAll();
    reader.close();//from ww w  .ja va  2s.  c  o m
    final Pattern accPattern = Pattern.compile("^[\\d ]*");
    final DecimalFormat formater = (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN);
    formater.setParseBigDecimal(true);
    //        final DecimalFormatSymbols frmSym = DecimalFormatSymbols.getInstance();
    //        frmSym.setDecimalSeparator(",".toCharArray()[0]);
    //        frmSym.setPatternSeparator(".".toCharArray()[0]);
    //        formater.setDecimalFormatSymbols(frmSym);

    for (final String[] row : rows) {
        final String accStr = row[0];
        if (!accStr.isEmpty() && accPattern.matcher(accStr).matches()) {
            final Account acc = new Account();
            ret.add(acc);
            acc.setName(accStr.trim());
            final String amountMEDebit = row[10];
            final String amountMECredit = row[11];
            final String amountMNDebit = row[12];
            final String amountMNCredit = row[13];
            if (!amountMEDebit.isEmpty()) {
                acc.setAmountME(((BigDecimal) formater.parse(amountMEDebit)).negate());
            }
            if (!amountMECredit.isEmpty()) {
                acc.setAmountME((BigDecimal) formater.parse(amountMECredit));
            }
            if (!amountMNDebit.isEmpty()) {
                acc.setAmountMN(((BigDecimal) formater.parse(amountMNDebit)).negate());
            }
            if (!amountMNCredit.isEmpty()) {
                acc.setAmountMN((BigDecimal) formater.parse(amountMNCredit));
            }
            ConSis.LOG.info("Read Account {} - Rate: {}", acc, acc.getRate());
        }
    }
    return ret;
}

From source file:org.jbpm.formModeler.core.processing.fieldHandlers.NumericFieldHandler.java

public Object getTheValue(Field field, String[] paramValue, String desiredClassName) throws Exception {
    if (paramValue == null || paramValue.length == 0)
        return null;

    if (desiredClassName.equals("byte")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Byte((byte) 0);
        else//from ww  w  . j  av a 2  s .  co  m
            return Byte.decode(paramValue[0]);
    } else if (desiredClassName.equals("short")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Short((short) 0);
        else
            return Short.decode(paramValue[0]);
    } else if (desiredClassName.equals("int")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Integer(0);
        else
            return Integer.decode(paramValue[0]);
    } else if (desiredClassName.equals("long")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Long(0L);
        else
            return Long.decode(paramValue[0]);
    } else if (desiredClassName.equals(Byte.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Byte.decode(paramValue[0]);
    } else if (desiredClassName.equals(Short.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Short.decode(paramValue[0]);

    } else if (desiredClassName.equals(Integer.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Integer.decode(paramValue[0]);

    } else if (desiredClassName.equals(Long.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Long.decode(paramValue[0]);

    } else if (desiredClassName.equals(Double.class.getName()) || desiredClassName.equals("double")
            || desiredClassName.equals(Float.class.getName()) || desiredClassName.equals("float")
            || desiredClassName.equals(BigDecimal.class.getName())) {

        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();

        DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(new Locale(LocaleManager.currentLang()));
        if (desiredClassName.equals(BigDecimal.class.getName()))
            df.setParseBigDecimal(true);
        String pattern = getFieldPattern(field);
        if (pattern != null && !"".equals(pattern)) {
            df.applyPattern(pattern);
        } else {
            df.applyPattern("###.##");
        }
        ParsePosition pp = new ParsePosition(0);
        Number num = df.parse(paramValue[0], pp);
        if (paramValue[0].length() != pp.getIndex() || num == null) {
            log.debug("Error on parsing value");
            throw new ParseException("Error parsing value", pp.getIndex());
        }

        if (desiredClassName.equals(BigDecimal.class.getName())) {
            return num;
        } else if (desiredClassName.equals(Float.class.getName()) || desiredClassName.equals("float")) {
            return new Float(num.floatValue());
        } else if (desiredClassName.equals(Double.class.getName()) || desiredClassName.equals("double")) {
            return new Double(num.doubleValue());
        }
    } else if (desiredClassName.equals(BigInteger.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return new BigInteger(paramValue[0]);

    }
    throw new IllegalArgumentException("Invalid class for NumericFieldHandler: " + desiredClassName);
}