简体   繁体   中英

how to identify if a number is of float or double type in java

How 19.5 is a double value. Why we need to append F to it to make it float ? Just want to know how we identify a number whether it is float or double .

19.5 is a floating-point literal in java. Quote from Java Language Specification #3.10.2 :

A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise, its type is double and it can optionally be suffixed with an ASCII letter D or d.


Now when we know that 19.5 is of type double, let's look at your example in the comments:

float value = 19.5;

Conversion from double to float in java is a narrowing primitive conversion . 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 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. 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). 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM