问题
I have some double numbers that are outputted with this format:
Format.String("%1.4e",doubleNumber);
The result is 1.123456e+03. How can I set the number of cipher of exponent for getting this format:
1.123456e+003
I would have always 3 cipher after e symbol.
Thank you
UPDATE 1:
I have partially resolved:
DecimalFormat formatter = new DecimalFormat("0.000000E000");
System.out.println( formatter.format(doubleNumber) );
Now the number has always the format
1.123456e0xx
or
1.123456e-0xx
But it's not all resolved. I would have always printed the sign:
1.123456e+0xx or 1.123456e-0xx
How can I do? http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
回答1:
Thank you @TDG
private String formatter(double number){
DecimalFormat formatter = new DecimalFormat("0.000000E000");
String fnumber = formatter.format(number);
if (!fnumber.contains("E-")) { //don't blast a negative sign
fnumber = fnumber.replace("E", "E+");
}
return fnumber;
}
回答2:
There's no built-in way to do that, you'd have to do it yourself.
Easiest would be to format like you did and then add the extra zeroes, if needed.
Also, it's String.format, not Format.String, and the "%1.4e" format you gave will result in 1.1235e+03, not 1.123456e+03.
回答3:
There's nothing that I can see in the String or Formatter JavaDoc that allows you to do this directly. So I think you'll have to resort to some bit twiddling.
long exponentMask = 0x7ff0000000000000L; // per JavaDoc for Double
// the exponent is in bits 62-52, so I'm thinking a right-shift by 52
// bits would work. But I could be off by one.
int shiftExponentBy = 52;
long myDoubleAsLong = Double.doubleToLongBits(doubleNumber);
long rawExponent = myDoubleAsLong & exponentMask;
long shiftedExponent = rawExponent >> shiftExponentBy;
That gives you the exponent by itself. You should be able to extract the significand in a similar manner, then format each separately.
Update 1
It seems as though your Update 1 results in the same problem, just expressed differently. You need to format the exponent separately from the significand. DecimalFormat allows a positive pattern and a different negative pattern, but those are for positive and negative significands. You'd need a variant on those that allows for positive and negative exponents. I don't see any such thing. I'm standing by my original answer.
来源:https://stackoverflow.com/questions/32722349/java-output-double-numbers-in-exponential-format