-2

here's a piece of Java code:

 import java.util.*;

public class javaTests
{
    public static void main(String[] args)
    {
        double decimal = 0.60;

        System.out.println(decimal);
    }
}

I'm trying to print 0.60, but the compiler prints 0.6. How can I get this to print 0.60? Thanks!

Panther
  • 3,312
  • 9
  • 27
  • 50
BjC
  • 43
  • 5
  • 1
    try `System.out.println(String.format( "%.2f", decimal ) );` – singhakash Apr 01 '15 at 17:09
  • Thank you @singhakash, this worked perfectly! could you briefly explain what `String.format` does? – BjC Apr 01 '15 at 17:17
  • See the java formatter class http://docs.oracle.com/javase/7/docs/api/index.html?java/util/Formatter.html %[flags][width][.precision]conversion "." is for padding , 2 specifies the number of digits and f for float – Chandru Apr 01 '15 at 17:25
  • @BjC sorry for the late reply did you check the [docs](http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax).Its better explaines there – singhakash Apr 01 '15 at 17:46
  • possible duplicate of [Round double value to 2 decimal places](http://stackoverflow.com/questions/4985791/round-double-value-to-2-decimal-places) – durron597 Apr 01 '15 at 19:25

3 Answers3

1
NumberFormat formatter = new DecimalFormat("#0.00");
double decimal = 0.60;
System.out.println(formatter.format(decimal));
singhakash
  • 7,891
  • 6
  • 31
  • 65
Ozgen
  • 1,072
  • 10
  • 19
0

You can't, the way you were trying to do it. A double only stores a number, it doesn't store the precision that number was written with. You can change the formatting of the output (e.g. System.out.printf("%.2f", value), or you can store the value in a different data type (e.g. BigDecimal, which does draw that distinction), but there is no difference in the double value 0.6 and the double value 0.60.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
0

You can also format using the String class.

System.out.println(String.format("%1.2f",.60));

The format method takes multiple parameters. The first argument is always the format string, which uses below syntax.

%[argument_index$][flags][width][.precision]conversion

Please refer to the java documentation for detail information on Formatter

http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

Himanshu Ahire
  • 677
  • 5
  • 18