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
It’s ugly to capture
Exception
. Ugly and dangerous. Capture just the exceptions you expect.– Pablo Almeida
http://answall.com/q/40045/101
– Maniero
How we need a
tryParse
java...– user28595