Question

If I perform

  97346822*3f, result is 2.9204048E8,

however

 97346822*3.0 gives me 2.92040466E8.

Please explain.

Était-ce utile?

La solution

The number 3.0 is the literal representation of a double value (it's equivalent to 3.0d), whereas 3.0f is a float value. The different precisions explain why you're getting different results - a double is stored using 64-bits, a float uses 32-bits.

Autres conseils

97346822*3.0

will be treated as double.

Based on oracle tutorial

The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice.

97346822*3f

will be treated as float.

These are findings related to this question and my answer to same.

While 3.0 and 3f both have the same value when put into floating point values, the actual value is used as working memory for the floating point operation. The internal values that are part of the multiplication do not fit into the floating point value themselves and are modified, resulting in a difference of 14.0 between the obtained results.

There is a concept called as Numeric promotion in Java

Numeric promotions are used to convert the operands(of an operation like multiplication, etc) of a numeric operator to a common type(smaller numeric type to a larger numeric type among the 2 datatypes of operands) to perform a specific operation

So in the example given by you, for 97346822*3f since the 3f is a float value so the floating point operation is done and the result is of float type.

But 3.0 is a double type which has higher range and precision which causes the results to vary

So the value of 3.0 and 3f are same, but when these values are used in a numeric operation then the result will vary based on the datatype of the other operand

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top