problems to print a double number

Asked

Viewed 787 times

2

I’m having trouble printing a double number, for example I create a double type variable, and this gets a 1/3 split, it would have to show 0.3, what I have to do to print 0.3???

public class MeuTeste{ 

public static void main(String [] a){ 
         double x=1;  
         double y=3;  
         System.out.println(x/y); 
    } 
} 
//0.3333333333333333

3 answers

6

One more way to format the output value:

double x=1;  
double y=3;
double resultado = x/y;
System.out.format("%10.1f%n", resultado);

2


Use the Bigdecimal class.

double variavel = 0.3333333333333333;
BigDecimal bd = new BigDecimal(variavel);  
bd = bd.setScale(1, BigDecimal.ROUND_HALF_EVEN);  
System.out.println(bd.toString()); 
  • Thank you that worked for me.

  • you have the Lync open?

2

If you just want to truncate the value to one decimal place, you can do so:

DecimalFormat df = new DecimalFormat("#.#");
System.out.println(df.format(x/y));

Browser other questions tagged

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