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
  • 24,498
  • 34
  • 108
  • 169

2 Answers2

5

You want String.format

String value = String.format("%.2f", doubleValue);
MadProgrammer
  • 336,120
  • 22
  • 219
  • 344
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,662
  • 1
  • 18
  • 41