[英]how to identify if a number is of float or double type in java
How 19.5 is a double value. 19.5如何成为双精度值。 Why we need to append
F
to it to make it float
? 为什么我们需要在它后面附加
F
使其float
? Just want to know how we identify a number whether it is float
or double
. 只想知道我们如何识别一个数字,无论它是
float
还是double
。
19.5
is a floating-point literal in java. 19.5
是Java中的浮点文字。 Quote from Java Language Specification #3.10.2 : 引用Java语言规范#3.10.2 :
A floating-point literal is of type float if it is suffixed with an ASCII letter F or f;
如果浮点文字后缀为ASCII字母F或f,则其类型为float。 otherwise, its type is double and it can optionally be suffixed with an ASCII letter D or d.
否则,其类型为double,并且可以选择在其后缀ASCII字母D或d。
Now when we know that 19.5
is of type double, let's look at your example in the comments: 现在,当我们知道
19.5
是double类型时,让我们在注释中查看您的示例:
float value = 19.5;
Conversion from double
to float
in java is a narrowing primitive conversion . Java中从
double
到float
转换是一种狭窄的原始转换 。 This type of conversion should be explicit. 这种类型的转换应该是明确的。 That's why you need to use floating-point literal of type
float
to get rid of the conversion 这就是为什么您需要使用
float
类型的float
文字来摆脱转换的原因
float value = 19.5f;
or to make this conversion explicit 或明确表示此转换
float value = (float) 19.5;
For handling downcasts, or narrowing conversions. 用于处理垂头丧气或缩小转换范围。 Whenever you downcast a long to an int, or a double to a float, the possibility for data loss exists.
每当将long转换为int或将double转换为float时,都存在数据丢失的可能性。 So, the compiler will force you to indicate that you really want to perform the narrowing conversion, by signaling a compile error for something like this:
因此,编译器将通过发出类似以下内容的编译错误来迫使您指示您确实要执行缩小转换:
float f = 19.5;
Because 19.5 represents a double, you have to explicitly cast it to a float (basically signing off on the narrowing conversion). 由于19.5代表双精度型,因此您必须将其显式转换为浮点型(基本上在缩小转换上签名)。 Otherwise, you could indicate that the number is really a float, by using the correct suffix;
否则,通过使用正确的后缀,您可以指示该数字实际上是一个浮点数;
float f = 19.5f;
by default 19.5 is double literal, So to tell compiler to treat it as float explicitly -> it uses f or F 默认情况下19.5是双字面量,因此要告诉编译器将其显式视为float->它使用f或F
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.