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.
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.
avarage.replaceAll(0, "");
UPD
DecimalFormat format = new DecimalFormat(); format.setDecimalSeparatorAlwaysShown(false); Double d = 1.4000; System.out.println( format.format(d) );
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 ) ; }
Source: https://ru.stackoverflow.com/questions/136230/
All Articles