Hello guys. There is a double res number, say, 0.1321231; . How to display only 0.13 ?

I know that you can derive as follows:

 System.out.printf("%.2f", res); 

but just what does it mean? How can I output standard via System.out.println ?

3 answers 3

printf means formatting a string in addition to output, that's all. To get a formatted string without output, use String.format ().

 String formattedDouble = String.format("%.2f", 0.1321231); 

http://docs.oracle.com/javase/tutorial/java/data/numberformat.html

    Slightly more correct and faster will use DecimalFormat .

     String formattedDouble = new DecimalFormat("#0.00").format(0.1321231); 

    Of course, the "#0.00" format string should be placed somewhere in a constant, possibly common to the entire application.

    Totally dragging the new DecimalFormat("#0.00") object into a constant, on the contrary, is not worth it for thread safety reasons.

    The performance gain compared to String.format() can be about 2 times. Plus DecimalFormat uses locale settings for the separator between the integer and fractional parts.

       String formattedDouble = new DecimalFormat("#0.00").format(0.1321231); 

      This method perfectly leaves two digits after the decimal point.