Java Tutorial/Data Type/Float Point Data Type

Материал из Java эксперт
Перейти к: навигация, поиск

Applying the modulus operator, %, to floating-point values

   <source lang="java">

public class MainClass{

 public static void main(String[] arg){
    double a = 2.4;
    double b = 0.2;
    
         
    System.out.println( a % b );
 }

}</source>



0.1999999999999998


Floating-Point Calculations

The four arithmetic operators: +, -, *, /.



   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   double numA = 50.0E-1;   // 5.0
   double numB = 1.0E1;     // 10.0
   double averageC = 0.0;
   averageC = (numA + numB) / 2.0;
   
   System.out.println(averageC);
 }

}</source>



7.5


Floating-Point Data Types: memory and length

Type float and type double are two primitive floating-point types in Java.

Data TypeDescriptionMemoryfloat-3.4E38 to +3.4E384 bytes in memorydouble-1.7E308 to +1.7E3088 bytes in memory

Examples of float literals include the following:



   <source lang="java">

2elf 8.f .5f 0f 3.14f 9.0001e+12f</source>





Using ++ and -- with floating-point variables

   <source lang="java">

public class MainClass{

 public static void main(String[] arg){
    double a = 12.12;
    
    System.out.println( a-- );
    System.out.println( a++ );
    System.out.println( --a );
    System.out.println( ++a );
 }

}</source>



12.12
11.12
11.12
12.12


Write Floating-Point Literals with an exponent

Write the number as a decimal value followed by an E, or an e.

  1. Floating-point literals are of type double by default.
  2. To specify a value of type float, you append an f, or an F.



   <source lang="java">

public class MainClass{

 public static void main(String[] arg){
    double f1 = 1.496E8;
    double f2 = 9.0E-28; 
 
    System.out.println(f1);
    System.out.println(f2);
    System.out.println(f2 + f1);
 }

}</source>



1.496E8
9.0E-28
1.496E8