0

How can I format a string in Java when I'm not printing it?

Eg. in Python I can do :

s = "%f" % f

All the Java examples I'm seeing online are using printf or some streams. How can I just create a formatted string internally?

interstar
  • 26,048
  • 36
  • 112
  • 180

2 Answers2

5

You want String.format

String value = String.format("%.2f", doubleValue);
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

You can use the String Formatter class:

http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html

public class Format {

   public static void main(String[] args) {
        String s = String.format("%f ", myfloat);
}

}

user1018513
  • 1,682
  • 1
  • 20
  • 42