I'm familiar with java.text.DecimalFormat it stinks.
I need to format a double to fit into a certain sized space in a display.
Unfortunately, I don't know the magnitude of the number. Sometimes it may
be very small, O(1e-6), other times, O(1), and sometimes very large O(1e6).
What I need is a way to specify the overall width of the formatted number.
Or possibly the number of significant digits.
That way, It will be smart enough to format the following numbers in a sane
manner (as shown)....
-2.342e-5
3.425
6432.431
6.235e8
The problem with DecimalFormat and the other Java solutions I've found is
that they ask you to explicitly define the numeric format, you can't just
specify the width or precision.
In C, what I'd like to do is "% 5.3g" The g switches between fixed and
scientific notation.
Fortran also has a similar expression.
Any help is appreciated,
Rob
Boudewijn Dijkstra - 13 Dec 2005 16:57 GMT
> I'm familiar with java.text.DecimalFormat it stinks.
>
> [...]
>
> In C, what I'd like to do is "% 5.3g" The g switches between fixed and
> scientific notation.
Have you tried String.format("%5.3g", d) ?
Rob McDonald - 13 Dec 2005 17:29 GMT
> > I'm familiar with java.text.DecimalFormat it stinks.
> >
[quoted text clipped - 4 lines]
>
> Have you tried String.format("%5.3g", d) ?
Thanks for the tip,
String.format("%10.4g", d)
Worked nicely for what I wanted. It would be nice if one could abbreviate
the exponent in the scientific notation, but I'll take it (i.e. 1.23e+04
would be prettier written as 1.23e4).
Thanks,
Rob
Mark Thomas - 13 Dec 2005 17:16 GMT
Rob
java.util.Formatter has the ability to do what you want, as has the
method printf() - a method of PrintWriter & PrintStream since Java 1.5
Mark
> I'm familiar with java.text.DecimalFormat it stinks.
>
[quoted text clipped - 25 lines]
>
> Rob