How can I represent smaller Double variables with exponents in java
For example:
double a = 2000; System.out.println(a);
Prints out 2000.0, whereas I would like to print 2E3. With a double of 2 I desire 2E0 etc.
I know that it begins to print like this when you reach 2000000开发者_高级运维0 (2E7) and would like to do it for any value of Double. Is there some libairy/function to do this? I've spent some hours looking through google results to no avail. I get the impression this may be possible by heavily manipulating the .toHexCode() output but I couldn't get my head around the documentation of its output. How would I go about doing this?
Have a look at the docs for DecimalFormat, that should do what you need.
EDIT: here's an example (haven't checked this):
double myDouble = 2000;
NumberFormat formatter = new DecimalFormat("0E0");
System.out.println(formatter.format(myDouble)); // Should print "2E3"
This prints 2E3. More on DecimalFormat class here.
double a = 2000;
DecimalFormat formatter = new DecimalFormat("###E0");
System.out.println(formatter.format(a));
That sounds like a job for java.util.Formatter. I haven't used it myself, but it seems capable of scientific notation. API entry is here: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
精彩评论