Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the "f" required when declaring floats?

Example:

float timeRemaining = 0.58f; 

Why is the f is required at the end of this number?

like image 254
Thomas Avatar asked Jul 17 '12 09:07

Thomas


People also ask

Why do floats need f?

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.

How do you declare a float?

You can define a variable as a float and assign a value to it in a single declaration. For example: float age = 10.5; In this example, the variable named age would be defined as a float and assigned the value of 10.5.

Why are floats not exact?

Floating-point decimal values generally do not have an exact binary representation due to how the CPU represents floating point data. For this reason, you may experience a loss of precision, and some floating-point operations may produce unexpected results.

What is the purpose of floats?

Floating has been shown to loosen the muscles and give more control over your nervous system. This reduces the risk of injury during training or competition.


1 Answers

Your declaration of a float contains two parts:

  1. It declares that the variable timeRemaining is of type float.
  2. It assigns the value 0.58 to this variable.

The problem occurs in part 2.

The right-hand side is evaluated on its own. According to the C# specification, a number containing a decimal point that doesn't have a suffix is interpreted as a double.

So we now have a double value that we want to assign to a variable of type float. In order to do this, there must be an implicit conversion from double to float. There is no such conversion, because you may (and in this case do) lose information in the conversion.

The reason is that the value used by the compiler isn't really 0.58, but the floating-point value closest to 0.58, which is 0.57999999999999978655962351581366... for double and exactly 0.579999946057796478271484375 for float.

Strictly speaking, the f is not required. You can avoid having to use the f suffix by casting the value to a float:

float timeRemaining = (float)0.58; 
like image 94
Jeffrey Sax Avatar answered Sep 26 '22 16:09

Jeffrey Sax