How to convert float to double in Java?

See English answers > why converting from float to double changes the value? 9

public class DataTypes

{
    static public void main(String[] args)
    {
        float a=1;
        float b=1.2f;
        float c=12e-1f;
        float x=1.2f;
        double y=x;

        System.out.println("float a=1 shows a= "+a+"\nfloat b=1.2f shows b= "+b+"\nfloat c=12e-1f shows c= "+c+"\nfloat x=1.2f shows x= "+x+"\ndouble y=x shows y= "+y);
    }
}

You can see the output here:

float a=1 shows a= 1.0
float b=1.2f shows b= 1.2
float c=12e-1f shows c= 1.2
float x=1.2f shows x= 1.2
double y=x shows y= 1.2000000476837158

Solution

The reason for this problem is that the computer only works in discrete mathematics, because the microprocessor can only represent all internal numbers, but there are no decimals Because we can not only use these numbers, but also use decimals to avoid this. Decades ago, very smart engineers invented floating-point representation and standardized it to IEEE754

The IEEE 754 specification defines how to interpret floating point numbers and double precision numbers in memory Basically, unlike ints that represent exact values, floating-point numbers and doubles are calculated from the following:

>Signature > index > score

So the problem here is that when you store 1.2 as double, you actually store the binary approximation:

00111111100110011001100110011010

It gives the closest representation to 1.2 and can be stored using binary fractions, but not exactly that fraction In the decimal part, 12 * 10 ^ - 1 gives the exact value, but as a binary fraction, it cannot give the exact value

(see http://www.h-schmidt.net/FloatConverter/IEEE754.html Because I'm too lazy)

In fact, in both versions of Y and float, the actual value is 1.2000000476837158, but because the mantissa of float is small, the value represented is truncated before approximation, so you think it is an accurate value, not in memory

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>