out.printf("Srednee: %g\n", average); 

Displays the function, for example, 1.500000. How to get rid of extra zeros? Specify the number of decimal places - no need to suggest.

  • one
    There is some misunderstanding in the question: not every decimal fraction can be accurately represented as a binary one. See an example when it is not : 108.595, for example, is presented as 108.594999999999998863131622783839702606201171875. - AlexeyM
  • one
    And in my opinion, the question is not about a limited bit depth, but about how to remove the extra zeros, without using the format specifier precision specifier. - IronVbif pm

4 answers 4

 avarage.replaceAll(0, ""); 

UPD

 DecimalFormat format = new DecimalFormat(); format.setDecimalSeparatorAlwaysShown(false); Double d = 1.4000; System.out.println( format.format(d) ); 
  • double average; therefore average.replaceAll (0, ""); does not fit and can, please, in more detail a bit, novice at all. - risonyo
  • Well, it all depends on the case, for example, I would not do that, because this function will replace all zeros in the string (to take advantage of your version, you need to transfer the double to the string, remove the zeros - display it), I updated the answer, try differently, maybe it will work ... - Gorets

You can just

 out.printf("Srednee: " + 1.2600); 

Will be

 Srednee: 1.26 

    Code:

     import java.text.NumberFormat ; public class FormatDouble { public static void main ( String[] args ) { for ( int i = 0 ; i < 15 ; i++ ) { double value = (double) i / 3 ; System.out.println ( "'" + value + "' = '" + format ( value ) + "'" ) ; } } private static String format ( double value ) { return NumberFormat.getInstance ().format ( value ) ; } } 

    Result:

     '0.0' = '0' '0.3333333333333333' = '0,333' '0.6666666666666666' = '0,667' '1.0' = '1' '1.3333333333333333' = '1,333' '1.6666666666666667' = '1,667' '2.0' = '2' '2.3333333333333335' = '2,333' '2.6666666666666665' = '2,667' '3.0' = '3' '3.3333333333333335' = '3,333' '3.6666666666666665' = '3,667' '4.0' = '4' '4.333333333333333' = '4,333' '4.666666666666667' = '4,667' 

      The solution to the problem from the respected jmu is quite good and very elegant. BUT! The format method from double returns a String, the comma in which is a separator (in our regions), which makes it impossible to cast back from String to double. It is necessary to localize .getInstance ()

       private static String format ( double value ) { return NumberFormat.getInstance (Locale.US).format ( value ) ; }