problems printing a double number

2

I'm having trouble printing a double number, for example I create a variable of type double, and it receives the one division 1/3, it would have to show 0.3, What do 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
    
asked by anonymous 20.02.2014 / 15:35

3 answers

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()); 
    
20.02.2014 / 15:37
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);
    
20.02.2014 / 15:44
2

If you just want to truncate the value to a decimal place, you can do this:

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