Convert float or double in real $

Asked

Viewed 8,768 times

10

I have a float = 11.6 I want to convert into Brazilian currency R$ 11,60, someone knows how to do?

2 answers

17


I usually use getCurrencyInstance with Locale set manually because when I don’t set it takes Operating System time and can certainly make a wrong conversion from real to dollar for example.

Double d = 10.1;
Locale ptBr = new Locale("pt", "BR");
String valorString = NumberFormat.getCurrencyInstance(ptBr).format(d);
System.out.println(valorString);

6

There are some ways to do it, for example:

BigDecimal valor = new BigDecimal ("12000000.12");  
NumberFormat nf = NumberFormat.getCurrencyInstance();  
String formatado = nf.format (valor);
System.out.println(formatado);
//O resultado é R$ 12.000.000,12

Other option:

Long a = Long.parseLong("999999999999999999");
System.out.println(NumberFormat.getCurrencyInstance().format(a));
//saída R$ 999.999.999.999.999.999,00
  • 1

    Is Numberformat reliable? If I’m going to use on Android depending on the user’s settings this may vary no?

  • 2

    has a look at the android documentation: http://developer.android.com/reference/java/text/NumberFormat.html

  • 1

    @Mateuscarvalho will vary if you do not use Locale. Otherwise I see no problem.

Browser other questions tagged

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