Floating point Type
|
strong> type |
takes up storage |
Table number range |
|
F Strong>loat |
4 bytes |
-3.403e38~3.403e38 |
|
D ouble |
8 |
-1.798e308~1.798e308 |
The float type is also known as the single-precision type, the Mantissa can be accurate to 7 significant digits , and in many casesthe precision of the float type is difficult to meet.
Double means that the numeric precision of this type is twice times the type of float, also known as double precision, and most applications take double types.
There are two representations of Java floating-point type constants
decimal number form, for example :
3.14 314.0 0.314
The form of scientific notation, such as
314e2 314E2 314E-2
double f = 314e2; // 314*10^2-->31400.0 Double // 314*10^ ( -2)-->3.14
the value of the float type has a suffix of f/f , and The floating-point value without the suffix f/f defaults to The double type . You can also add a suffix d/d after a floating-point value to make it clear that it is a double type:
floating-point type float, double data does not fit in the financial calculation area where rounding errors are not tolerated.
If you need to do not produce a rounding error Accurate numeric calculations require the use of the BigDecimal class .
Note:
main reasons: Because of the limited length of the word, the number of floating-point numbers that can be accurately represented is finite and therefore discrete. Floating-point numbers generally have rounding errors, many of which cannot be represented accurately ( for example , 0.1), and the result can only be close, but not equal.
A binary floating-point number cannot accurately represent A negative power of 0.1,0.01,0.001. Not all decimals can be accurately represented by binary floating-point numbers
It's best to avoid floating-point comparisons altogether . :
Public classtestfloattype{ Public Static voidMain (string[] agrs) {floatA = 0.1f; Doubleb = 1.0/10; System.out.println (A==B);//execution result is false floatc =278390f; floatE = c+1; if(c==e) {System.out.println ("C equals E"); } Else{System.out.println ("C is not equal to E"); } //execution result is c not equal to E }}
Large value:
Java.math The following two useful classes:BigInteger and BigDecimal, these two classes can handle values of any length. BigInteger implements an integer operation of arbitrary precision. BigDecimal implements a floating point operation with arbitrary precision.
Floating Point Usage Summary:
- default is double
- There are rounding errors in floating-point numbers, many of which cannot be represented accurately. If you need an exact numeric calculation that does not produce rounding errors, you need to use the BigDecimal class.
-
Avoid using floating-point numbers in comparisons
"Java" java_07 floating-point type