Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a primitive float value be -0.0? What does that mean?

How come a primitive float value can be -0.0? What does that mean?
Can I cancel that feature?

When I have:

  float fl;   

Then fl == -0.0 returns true and so does fl == 0. But when I print it, it prints -0.0.

like image 257
Bick Avatar asked Jul 17 '11 13:07

Bick


People also ask

What is primitive float?

float: The float data type is a single-precision 32-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.

What is primitive type value?

In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods or properties. There are 7 primitive data types: string. number. bigint.

Is float a primitive data type?

Primitive data types - includes byte , short , int , long , float , double , boolean and char.

What is the default value of primitive datatype float?

Default value of int is 0 and float is 0.0f.


1 Answers

Because Java uses the IEEE Standard for Floating-Point Arithmetic (IEEE 754) which defines -0.0 and when it should be used.

The smallest number representable has no 1 bit in the subnormal significand and is called the positive or negative zero as determined by the sign. It actually represents a rounding to zero of numbers in the range between zero and the smallest representable non-zero number of the same sign, which is why it has a sign, and why its reciprocal +Inf or -Inf also has a sign.

You can get around your specific problem by adding 0.0

e.g.

Double.toString(value + 0.0); 

See: Java Floating-Point Number Intricacies

Operations Involving Negative Zero
...
(-0.0) + 0.0 -> 0.0

-

"-0.0" is produced when a floating-point operation results in a negative floating-point number so close to 0 that it cannot be represented normally.

like image 176
OldCurmudgeon Avatar answered Oct 10 '22 03:10

OldCurmudgeon