Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

formatter

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

like image 327
Bick Avatar asked Dec 12 '22 10:12

Bick


2 Answers

Here are two ways of dealing with 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);
}
like image 73
Tony Avatar answered Apr 08 '23 20:04

Tony


  double pi = Math.PI;
  System.out.format("%f%n", pi);    //  -->  "3.141593"    
  System.out.format("%.3f%n", pi);  //  -->  "3.142"

note: %n is for newline

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

like image 40
Armen Tsirunyan Avatar answered Apr 08 '23 20:04

Armen Tsirunyan