Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to write 0.0, 0.0f or .0f instead of simple 0 for supposed float or double values

Hello well all is in the title. The question apply especially for all those values that can be like NSTimeInterval, CGFloat or any other variable that is a float or a double. Thanks.

EDIT: I'm asking for value assignment not format in a string.

EDIT 2: The question is really does assigning a plain 0 for a float or a double is worst than anything with f a the end.

like image 461
Nicolas Manzini Avatar asked Jan 13 '13 11:01

Nicolas Manzini


People also ask

What does 0.0 F mean in C++?

'f' indicates that you want a float : 0 is an int. 0f is a float. 0.0 is a double. 0.0f is a float.

Why do we use F in float in Java?

Why is it used? The "F" indicates that the literal numeric value it is appended to is a float value. This is necessary information for the compiler and if not present can lead to errors or the compiler otherwise interpreting the number incorrectly.

What is the difference between 0 and 0f?

0, or 0.0f or even 0f does not make much of a difference. (There are some with respect to double and float) You may even use (float) 0. But there is a significant difference between 0 and some float notation. Zero will always be some type of integer.

What does .1f mean in Java?

If you write 1f it will be considered a float . If you write 1.0 (no f) it will default to a double . 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. For more info about java data types.


2 Answers

The basic difference is as :

1.0 or 1. is a double constant

1.0f is a float constant

Without a suffix, a literal with a decimal in it (123.0) will be treated as a double-precision floating-point number. If you assign or pass that to a single-precision variable or parameter, the compiler will (should) issue a warning. Appending f tells the compiler you want the literal to be treated as a single-precision floating-point number.

like image 57
Anoop Vaidya Avatar answered Sep 20 '22 08:09

Anoop Vaidya


If you are initializing a variable then it make no sense. compiler does all the cast for you.

float a = 0; //Cast int 0 to float 0.0
float b = 0.0; //Cast 0.0 double to float 0.0 as by default floating point constants are double
float c = 0.0f // Assigning float to float. .0f is same as 0.0f

But if you are using these in an expression then that make a lot of sense.

6/5 becomes 1
6/5.0 becomes 1.2 (double value)
6/5.0f becomes 1.2 (float value)
like image 35
Inder Kumar Rathore Avatar answered Sep 18 '22 08:09

Inder Kumar Rathore