An issue is raised when a higher-precision floating-point literal is explicitly converted to a lower-precision floating-point type using an explicit type conversion operation.

Why is this an issue?

In most languages, decimal number literals without a suffix are treated as a higher-precision floating-point type by default. When you need a lower-precision floating-point value, you have two options:

Using an explicit cast adds unnecessary complexity to the code. The cast operator signals a type conversion, which typically requires careful attention from readers to ensure no precision loss or unexpected behavior occurs. However, when casting a literal value, this concern disappears - the value is known at compile time.

Type-specific floating-point literals (decimal numbers with a suffix indicating the target type) were designed specifically for this purpose. They clearly express the intent that this is a value of the lower-precision type, not the default type being converted. This makes the code more readable and idiomatic.

Additionally, while the performance impact is minimal in most cases, using a type-specific literal avoids the runtime cast operation entirely, as the compiler directly treats the value as the intended type.

In Java specifically, use 3.14f instead of (float) 3.14, where the f or F suffix designates a float literal.

What is the potential impact?

This issue affects code readability and maintainability. While it does not introduce bugs or security vulnerabilities, it makes the code slightly harder to read and understand. The unnecessary type conversion adds visual noise and may cause readers to spend extra time verifying that the conversion is intentional and safe.

How to fix it

Replace the cast expression with a float literal by adding the f suffix to the number and removing the cast operator.

Code examples

Noncompliant code example

float value = (float) 3.14; // Noncompliant
float pi = (float) 3.14159;
float half = (float) 0.5;

Compliant solution

float value = 3.14f;
float pi = 3.14159f;
float half = 0.5f;

Resources

Documentation