0

My apologies if that was asked somewhere, but I couldn't find anything that would help me. This is part of my larger program when I want to add numbers and display them, but when I encountered number 0.6 output is not "accurate". I want to display them exactly to one decimal point. How I can achieve this ?

Source Code:

public class NumberTest {

    public static void main(String[] args){
        double n = 0.6;
        double sum = 0.0;
        for(int i = 0; i < 10; i++){
            System.out.println(sum);
            sum += n;
        }
    }
}

Output:

0.0
0.6
1.2
1.7999999999999998
2.4
3.0
3.6
4.2
4.8
5.3999999999999995
ashur
  • 4,177
  • 14
  • 53
  • 85

1 Answers1

3

Don't use println but rather printf(...) since printf allows for formatted output.

System.out.printf("%.1f%n", sum);

Or use a DecimalFormat object:

DecimalFormat df = new DecimalFormat("0.0");

System.out.println(df.format(sum));

And yeah, this is a duplicate question of a duplicate of a duplicate...

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • +1 I am sure it was a duplicate for languages around before Java. – Peter Lawrey Aug 08 '13 at 19:38
  • @PeterLawrey: Thanks. I'm trying to find the best duplicate because this question really should be closed and there should be a link to a duplicate with an appropriate accepted answer. As you know most of this was borrowed from C (which borrowed it from...?) – Hovercraft Full Of Eels Aug 08 '13 at 19:38
  • @PeterLawrey: here's a nice related question: [how-to-get-the-decimal-part-of-a-float](http://stackoverflow.com/questions/5017072/how-to-get-the-decimal-part-of-a-float). 1+ to the answer! – Hovercraft Full Of Eels Aug 08 '13 at 19:40