Performance and scalability: Java sprintf equivalent?
In C, the sprintf function will format a string, including integer values to a specific length. for example, you could do sprintf(%i03); and it would show 000 as part of the string. Is there a Java equivalent to this function?
- Posted by: Christopher Fowler
- Posted on: September 08 2000 15:08 EDT
- Java sprintf equivalent? by fengliang wu on September 08 2000 22:01 EDT
- Java sprintf equivalent? by Nikhil Ranjan Silsarma on September 11 2000 12:45 EDT
- Java sprintf equivalent? by Darryl Dawson on September 12 2000 17:00 EDT
- Java sprintf equivalent? by Praveen Coca on October 19 2000 08:48 EDT
- Java sprintf equivalent? by Christopher Fowler on October 24 2000 16:43 EDT
- Re: Java sprintf equivalent? by Anjan Bacchu on August 25 2006 14:58 EDT
- Java sprintf equivalent? by Doug Hurst on December 04 2011 18:25 EST
I am not sure, but it looks like there is no "sprintf-kind" functions (methods) in Java standard libraries. You can try to use some of the format classes from java.text package, for example: there is class java.text.DecimalFormat which can format decimal values to string based on the given format (mask).
In order to solve that we can use the following:
NumberFormat nf = NumberFormat.getInstance();
// say we need 3 digits
System.out.println("Number 1:"+ nf.format(1));
You might want to check this out:
There is a Java Class that implements this functionality that is made freely available on www.javasoft.com under Java Developers Connection. I gather from the articles that efforts are under way to support such functionality as part of J2SE/J2EE platform in future but in the mean time this class might meet your needs. It is available with full source code,examples and doc.The name of the class is PrintfFormat and the url is http://developer.java.sun.com/developer/technicalArticles/Programming/sprintf/
Hope this helps.
Thanks for all of the responses. I did find a Class called PrintfFormat on the javasoft site. It works well, you may want to check it out.
In C, the sprintf function will format a string, including integer values to a specific length. for example, you could do sprintf(%i03); and it would show 000 as part of the string. Is there a Java equivalent to this function?hi there, in java 5, there is a static method in the java.lang.String class called format(). it pretty much works the same as C's sprintf(). http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html BR, ~A
You've probably already figured this out, but you can use String.format() about like C's sprintf...
String mstr = String.format("%-25s %3s/%3s", sa.trim(),sa.trim(),sa.trim());
Hope this helps