How can I format a float in Java with a given number of digits after a decimal point?

What is the best way in Java to get a string from a float that contains only X digits after the dot?

+4
source share
3 answers

Here are two ways to solve the problem.

public static void main(String[] args) { final float myfloat = 1F / 3F; //Using String.format 5 digist after the . final String fmtString = String.format("%.5f",myfloat); System.out.println(fmtString); //Same using NumberFormat final NumberFormat numFormat = NumberFormat.getNumberInstance(); numFormat.setMaximumFractionDigits(5); final String fmtString2 = numFormat.format(myfloat); System.out.println(fmtString2); } 
+6
source
  double pi = Math.PI; System.out.format("%f%n", pi); // --> "3.141593" System.out.format("%.3f%n", pi); // --> "3.142" 

Note: %n for new line

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

+4
source

Is Float.toString() what are you after?

See also the Formatter class for an alternative method.

+3
source

All Articles