Java: Why we need to cast a float but not a double?

雨燕双飞 提交于 2020-04-07 01:04:14

问题


I don't know if you consider this an important question or not but I want to know. float is a float number (4 bytes). double is a float number (8 bytes). Why we define double wihtout casting:

double d = 2.1;

But we need to cast with floats:

float f = (float) 2.1;

or

float f = 2.1f;

Thank you in advance.


回答1:


A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double and it can optionally end with the letter D or d.

The floating point types (float and double) can also be expressed using E or e (for scientific notation), F or f (32-bit float literal) and D or d (64-bit double literal; this is the default and by convention is omitted).

double d1 = 123.4;
// same value as d1, but in scientific notation
double d2 = 1.234e2;
float f1  = 123.4f;

See Floating-Point Literals in oracle Java Tutorial




回答2:


Doubles are more precise and the extra storage cost is almost always negligible. So in Java by default 2.1 is a double type. Now to convert double to float you need to cast while assigning double data to double type cast is not required.




回答3:


By default, Java compiler perceives 2.1 as being a double (64 bits) and not as a float (32 bits). Declaring float f=2.1 would result in loss of precision. Hence, Java forces you to do the casting to make sure you are declaring a float variable.

Without casting, you can achieve the same with the letter 'f' at the end of floating point numbers. For example, float f=2.1f.

Now you might ask, why a cast isn't required while converting from a long to a float because the former uses more bits internally than the latter. The answer is Java needs no casting on a widening path - byte => short => int => long => float => double. (Left to right (a widening conversion) - cast is not required; Right to left (a narrowing conversion) - explicit cast is required)



来源:https://stackoverflow.com/questions/52069115/java-why-we-need-to-cast-a-float-but-not-a-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!