How can I get decimal points in java?

2

I need to show the user an amount to pay, but the result returned is the following 1700.292 , the user will find it an error.

You need to show the exact amount separated by points - > 1,700,292

  

Correct result: 1,700,292

     

Erroneous result that is what it gives me now: 1700.292

salaryMensual = 785.292

cestaTiket = 915,000

wageMensual + basketTiket; = 1,700,292

public class Prueba{
  public static void main(String[] args){

   double value1 = 785.292;

   double value2 = 915.000;

   System.out.println(BigDecimal.valueOf(value1 + value2));

   }

}

How can you use the class to achieve decimal points?

    
asked by HectoRperez 23.03.2018 в 04:13
source

3 answers

3

I think what you're looking for would be like this.

public class Prueba{
  public static void main(String[] args){

    DecimalFormat formateador = new DecimalFormat("###,###.##");

    double value1 = 785.292;

    double value2 = 915.000;

    System.out.println(formateador.format(value1 + value2));

   }
}

Remember to import the library from:

import java.text.DecimalFormat;
    
answered by 23.03.2018 в 04:32
1

You can format your number. Look at this example:

  public static void main(String[] args)
  {
    double value1 = 785.292;
    double value2 = 915.000;
    double value=value1+value2;
    java.text.NumberFormat nf = java.text.NumberFormat.getInstance(); 
    String valString = nf.format(value).replace(".",".");
    System.out.println(valString);
  }
    
answered by 23.03.2018 в 04:32
0

Consider using the locale for a correct format, depending on the region:

public static void main(String[] args) {
    Locale locale = new Locale("es");

    format(12345678.9, new DecimalFormat("#,###.##", DecimalFormatSymbols.getInstance(locale)));
    format(12345678.9, NumberFormat.getInstance(locale));
}

private static void format(double n, NumberFormat format) {
    System.out.print(n);
    System.out.print(" => ");
    System.out.println(format.format(n));
}
    
answered by 26.03.2018 в 17:33