Double format in Java

5

I have the following value 1234.0000 . I would like to format for the following output: 1.234,00 . There may be cases that I will also use 1.234,0 , but I believe doing for the first case the others are similar.

    
asked by anonymous 25.03.2015 / 14:27

2 answers

5

You can use DecimalFormat:

double d = 1243123.1;
DecimalFormat df = new DecimalFormat("###,###.00");
System.out.println(df.format(d));

Output:

  

1,243,123.10

However DecimalFormat uses the properties of its operating system to define the output format, for example, in Brazil we use , to separate the integer from the decimals, whereas in the USA the , serves to separate the thousands. In my OS the output was as I showed above, but depending on the OS it may come out a bit differently.

If you do not want to allow these variations of OS, you can use the Locale class to find your output, and you can even add money to the output if you are working with money.

Example:

double d = 1243123.1;

Locale localeBR = new Locale( "pt", "BR" );  
NumberFormat dinheiroBR = NumberFormat.getCurrencyInstance(localeBR);  
System.out.println(dinheiroBR.format(d));

Locale localePT = new Locale( "pt", "PT" );  
NumberFormat dinheiroPT = NumberFormat.getCurrencyInstance(localePT);  
System.out.println(dinheiroPT.format(d));

NumberFormat numeroBR = NumberFormat.getNumberInstance(localeBR);
numeroBR.setMinimumFractionDigits(2);
numeroBR.setMaximumFractionDigits(2);
System.out.println(numeroBR.format(d));

Locale localeUS = new Locale( "en", "US" );  
NumberFormat numeroUS = NumberFormat.getNumberInstance(localeUS);
numeroUS.setMinimumFractionDigits(2);
numeroUS.setMaximumFractionDigits(2);
System.out.println(numeroUS.format(d));

Output:

  

R $ 1,243,123.10
  1,243,123.10 €
  1,243,123.10
  1,243,123.10

    
25.03.2015 / 14:39
2

I resolved by defining characters to separate decimal places and groups:

    double d = 11356982.10000;

    DecimalFormat df = new DecimalFormat("###,###.00");
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();

    //define o caractere separador das casas decimais
    dfs.setDecimalSeparator(',');
    //define o caractere separador dos grupos das milhares
    dfs.setGroupingSeparator('.');
    //seta o formatador de simbolos ao formatador do decimal
    df.setDecimalFormatSymbols(dfs);

    String total = df.format(d);

For value 11356982.10000 result 11.356.982,10

    
25.03.2015 / 15:14