Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java strange rounding with DecimalFormat

Tags:

java

double number = Scanner.nextDouble();    
DecimalFormat df = new DecimalFormat("#.#");
        System.out.print (df.format(number));

I've tried the above for rounding my number to 1 decimal place but in cases where there are no decimal numbers, it seems to round to an integer value (for example 2.0 would be displayed as 2). I want 2.0, as well as any other input number to display in 1 decimal place. Also, when DecimalFormat rounds a negative number to 0, it turns it to -0. How can I solve these issues?

like image 227
rage against the computer Avatar asked Oct 20 '22 10:10

rage against the computer


1 Answers

Use "0.0" as your format string. # means a digit, or blank if zero which is what you're seeing.

For getting rid of the sign, take a look at this answer.

like image 51
Phil Anderson Avatar answered Oct 22 '22 02:10

Phil Anderson