Convert String to Float with Java comma

Asked

Viewed 5,127 times

8

How do I convert in an elegant way String for float java?

The strings are with the Brazilian localization, that is, the values come with comma as decimal separator ("12.345").

I find it so... "ugly" to wear

        String preco = request.getParameter("preco");
        try {                
            cadastro.setPreco(Float.valueOf(preco.replace(",", ".")));                
        } catch (Exception e)
        {
            cadastro.setPreco(0);
        }

I can’t believe that Java doesn’t have any location...?

  • 2

    It’s ugly to capture Exception . Ugly and dangerous. Capture just the exceptions you expect.

  • http://answall.com/q/40045/101

  • 1

    How we need a tryParse java...

1 answer

8


One of the ways I know is by using Numberformat:

public static void main(String[] args) {
    String numero = "199";
    System.out.println(NumberFormat.getCurrencyInstance().format(Float.parseFloat(numero)));
}

Iprime: R$ 199,00


Updated

To receive numbers with commas you can do as follows:

public static double converte(String arg) throws ParseException{
    //obtem um NumberFormat para o Locale default (BR)
    NumberFormat nf = NumberFormat.getNumberInstance(new Locale("pt", "BR"));
    //converte um número com vírgulas ex: 2,56 para double
    double number = nf.parse(arg).doubleValue();
    return number;
}

public static void main(String[] args) throws ParseException {
    String numero = "199,99";
    BigDecimal bg = new BigDecimal(converte(numero)).setScale(2, RoundingMode.HALF_EVEN);
    System.out.println(bg);
}

I edited the answer and made a conversion of the value to BigDecimal, which is the most recommended format for working with currencies. In the future you can refactor your code and work directly with the BigDecimal. That method converte may be a method of Utility Class.

See it working on Ideone: https://ideone.com/cZ73CB

  • 2

    and put a comma in that string?

  • 1

    @Diegof I edited the answer :p

  • 2

    The line NumberFormat nf = NumberFormat.getNumberInstance(); must be NumberFormat nf = NumberFormat.getNumberInstance(new Locale("pt", "BR");. Do not assume that your VM will be in en en by default.

  • Thank you @josivan, added in reply :p

  • 1

    Corretíssimo @josivan. At all times define the locale. A good program is locale-Aware and all routines must define Locale to avoid unexpected behavior, including date, number, and text-related operations such as toLowerCase. Always refer to the API’s Javadoc and prefer methods with Locale.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.