Convert String to Float with comma in Java

8

How do I gracefully convert String to float into java?

The strings are with the Brazilian location, that is, the values come with a comma as the decimal separator ("12,345").

I think so ... "ugly" to use

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

Can not believe that java has no location ... is there any way?

    
asked by anonymous 26.02.2016 / 13:23

1 answer

8

One of the ways I know it is using NumberFormat : p>

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 the following:

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 have edited the answer and converted 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 BigDecimal . This converte method can be a method of a Utility Class .

See working on Ideone: link

    
26.02.2016 / 13:29