I'm using Java's DecimalFormat class to print out numbers in Scientific Notation. However, there is one problem that I have. I need the strings to be of fixed length regardless of the value, and the sign on the power of ten is throwing it off. Currently, this is what my format looks like:
DecimalFormat format = new DecimalFormat("0.0E0");
This gives me the following combinations: 1.0E1, 1.0E-1, -1.0E1, and -1.0E-1.
I can use setPositivePrefix to get: +1.0E1, +1.0E-1, -1.0E1, and -1.0E-1, or whatever I like, but it doesn't affect the sign of the power!
Is there any way to do this so that I can have fixed length strings? Thanks!
Edit: Ah, so there's no way to do it using Java's existing DecimalFormat API? Thanks for the suggestions! I think I may have to subclass DecimalFormat because I am limited by the interface that is already in place.
How to use?
See
formatTest
method.if (value.compareTo(positive) == 1 || value.compareTo(negative) == -1)
is useful for very large numbersWhy not use "0.0E+0" pattern instead? Note the plus sign before last zero.
Could you use
printf()
instead:Output:
If you need to output to a
String
instead, you can use the information provided at Formatted Printing for Java (sprintf) to do that.EDIT: Wow, that
PrintfFormat()
thing is huge and seems to be unnecessary:I got the idea for the above code from Get an OutputStream into a String.
Here's one way. Hokey, perhaps, but it works...
Alternatively you could subclass DecimalFormat, but I find it generally cleaner not to subclass from concrete classes.
This worked form me,