I want to check the exponent of numbers generated in my program. (They are generated like 2.333E-4
, when I print). I want to check which numbers are having Exponent smaller than E-4
, which needs to be inc开发者_如何学Goreased by multiplying with 10 till they reach E-4
.
Any ideas how to achieve this? Even if someone can tell me how to extract the exponent , it will be helpful.
You can use Java docs: Double.doubleToRawLongBits
Double.doubleToRawLongBits
public static long doubleToRawLongBits(double value)
Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "double format" bit layout, preserving Not-a-Number (NaN) values.
Bit 63 (the bit that is selected by the mask 0x8000000000000000L) represents the sign of the floating-point number.
Bits 62-52 (the bits that are selected by the mask 0x7ff0000000000000L) represent the exponent.
Bits 51-0 (the bits that are selected by the mask 0x000fffffffffffffL) represent the significand (sometimes called the mantissa) of the floating-point number.
So you could get the double value into a long, shift by 13*4 (13 hex digits = 13*4 bits) to the right and check the exponent value that way.
This link will help with the decoding: IEEE754 double FP format - exponent encoding
Another way to extract the exponent is to use the logarithm (base 10) function (Math.log10(double a) in Java).
For the input value you give, it will return -3.6320852612062473. For the input value 1e-4, it will return -4. Therefore, here is what you could do (assuming that "number" is the double value you want to test in the code below):
while (Math.log10(number) < -4) {
number = number * 10;
}
You can do this
double d = 0.01234e-4;
if (d < 1e-4)
System.out.printf("%fE-4", d * 1e4);
else
System.out.printf("%g", d);
prints
0.012340E-4
精彩评论