|
Java does not have any built in equivalent to C's printf/sprintf/fprintf
family of functions that specify the width and precision of
numbers converted into strings. Since Java does not support variable length
argument lists, it's not possible to write exact equivalents for these
functions. Instead the approach that must be taken is to convert one number
at a time into a string according to a format specification,
then write the resulting string onto the appropriate output stream.
This is a more flexible solution, but it's far from obvious.
In Java 1.1, the java.text package contains classes
that format numbers according to particular needs. In particular it's worth
getting to know the java.text.NumberFormat and
java.text.DecimalFormat
classes, though these can't handle exponential notation.
I've begun work on my own formatting class that does handle exponential
and other notations available through printf(). It can be found at
http://metalab.unc.edu/javafaq/formatter/.
Gary Cornell and Cay Horstmann's popular book
Core Java
also includes such a class.
You can probably find more at Gamelan. |