Java Tutorial/Data Type/Double

Материал из Java эксперт
Версия от 15:26, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Compare Two Java double Arrays

import java.util.Arrays;
public class Main {
  public static void main(String[] args) {
    double[] a1 = new double[] { 1.3, 7.2, 4.2 };
    double[] a2 = new double[] { 1.3, 7.2, 4.2 };
    System.out.println(Arrays.equals(a1, a2));
  }
}





Convert double value to string and check the position of dot

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
public class ToStringDemo {
  public static void main(String[] args) {
    double d = 858.48;
    String s = Double.toString(d);
    int dot = s.indexOf(".");
    System.out.println(dot + " digits before decimal point.");
    System.out.println((s.length() - dot - 1) + " digits after decimal point.");
  }
}





Convert from double to String

public class Main {
  public static void main(String[] args) throws Exception {
    String str = Double.toString(23);
  }
}





Convert from String to double

public class Main {
  public static void main(String[] args) throws Exception {
    Double d = Double.valueOf("0.9D").doubleValue();
  }
}





Converting a String to a double type Number

public class Main {
  public static void main(String[] argv) throws Exception {
    double d = Double.parseDouble("123.4e10");
    System.out.println(d);
  }
}





Convert java Double to numeric primitive data types

public class Main {
  public static void main(String[] args) {
    Double dObj = new Double("10.50");
    byte b = dObj.byteValue();
    System.out.println(b);
    short s = dObj.shortValue();
    System.out.println(s);
    int i = dObj.intValue();
    System.out.println(i);
    float f = dObj.floatValue();
    System.out.println(f);
    double d = dObj.doubleValue();
    System.out.println(d);
  }
}
/*
10
10
10
10.5
10.5
*/





Convert Java String to Double

public class Main {
  public static void main(String[] args) {
    Double dObj1 = new Double("100.564");
    System.out.println(dObj1);
    Double dObj2 = Double.valueOf("10.6");
    System.out.println(dObj2);
    double d = Double.parseDouble("76.39");
    System.out.println(d);
  }
}





Create a Double object using one of the below given constructors

public class Main {
  public static void main(String[] args) {
    double d = 10.10;
    Double dObj1 = new Double(d);
    System.out.println(dObj1);
    Double dObj3 = new Double("25.34");
    System.out.println(dObj3);
  }
}





Decimal Format

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.text.DecimalFormat;
public class DecimalFormatDemo {
  static public void customFormat(String pattern, double value) {
    DecimalFormat myFormatter = new DecimalFormat(pattern);
    String output = myFormatter.format(value);
    System.out.println(value + "  " + pattern + "  " + output);
  }
  static public void main(String[] args) {
    customFormat("###,###.###", 123456.789);
    customFormat("###.##", 123456.789);
    customFormat("000000.000", 123.78);
    customFormat("$###,###.###", 12345.67);
  }
}





Demonstrate isInfinite() and isNaN()

class InfNaN {
  public static void main(String args[]) {
    Double d1 = new Double(1/0.);
    Double d2 = new Double(0/0.);
   
    System.out.println(d1 + ": " + d1.isInfinite() + ", " + d1.isNaN());
    System.out.println(d2 + ": " + d2.isInfinite() + ", " + d2.isNaN());
  }
}





Double value

class DoubleDemo {
  public static void main(String args[]) {
    Double d1 = new Double(3.14159);
    Double d2 = new Double("314159E-5");
   
    System.out.println(d1 + " = " + d2 + " -> " + d1.equals(d2));
  }
}





Format double with System.out.format

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.util.Calendar;
import java.util.Locale;
public class TestFormat {
  public static void main(String[] args) {
    long n = 461012;
    System.out.format("%d%n", n);
    System.out.format("%08d%n", n);
    System.out.format("%+8d%n", n);
    System.out.format("%,8d%n", n);
    System.out.format("%+,8d%n%n", n);
    double pi = Math.PI;
    System.out.format("%f%n", pi);
    System.out.format("%.3f%n", pi);
    System.out.format("%10.3f%n", pi);
    System.out.format("%-10.3f%n", pi);
    System.out.format(Locale.FRANCE, "%-10.4f%n%n", pi);
    Calendar c = Calendar.getInstance();
    System.out.format("%tB %te, %tY%n", c, c, c);
    System.out.format("%tl:%tM %tp%n", c, c, c);
    System.out.format("%tD%n", c);
  }
}





How to declare floating-point variables: double

public class MainClass {
  public static void main(String[] arg) {
    double sunDistance = 1.496E8;
    System.out.println(sunDistance);
  }
}



1.496E8


Java Double compare example

public class Main {
  public static void main(String[] args) {
    double d1 = 5.5;
    double d2 = 5.4;
    int i1 = Double.rupare(d1, d2);
    if (i1 > 0) {
      System.out.println(">");
    } else if (i1 < 0) {
      System.out.println("<");
    } else {
      System.out.println("=");
    }
    Double dObj1 = new Double("5.5");
    Double dObj2 = new Double("5.4");
    int i2 = dObj1.rupareTo(dObj2);
    if (i2 > 0) {
      System.out.println(">");
    } else if (i2 < 0) {
      System.out.println("<");
    } else {
      System.out.println("=");
    }
  }
}





Java double: double is 64 bit double precision type and used when fractional precision calculation is required.

public class Main {
  public static void main(String[] args) {
    double d = 1234.56;
    System.out.println("Value of double variable d is :" + d);
  }
}
//Value of double variable d is :1234.56





Java Double isInfinite

public class Main {
  public static void main(String[] args) {
    double d = (double) 4 / 0;
    boolean b1 = Double.isInfinite(d);
    System.out.println(b1);
    Double dObj = new Double(d);
    boolean b2 = dObj.isInfinite();
    System.out.println(b2);
  }
}





Java Double isNaN method

public class Main {
  public static void main(String[] args) {
    double d = Math.sqrt(-10);
    boolean b1 = Double.isNaN(d);
    System.out.println(b1);
    Double dObj = new Double(d);
    boolean b2 = dObj.isNaN();
    System.out.println(b2);
  }
}





Min and Max values of data type double

public class Main {
    
    public static void main(String[] args) {
        System.out.println(Double.MIN_VALUE);
        System.out.println(Double.MAX_VALUE);
    }
}
/*
4.9E-324
1.7976931348623157E308
*/





Read double value from console and check the format

import java.io.BufferedReader;
import java.io.InputStreamReader;
class Main {
  public static void main(String args[]) throws Exception {
    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);
    while (true) {
      System.out.print("Radius? ");
      String str = br.readLine();
      double radius;
      try {
        radius = Double.valueOf(str).doubleValue();
      } catch (NumberFormatException nfe) {
        System.out.println("Incorrect format!");
        continue;
      }
      if (radius <= 0) {
        System.out.println("Radius must be positive!");
        continue;
      }
      System.out.println("radius " + radius);
      return;
    }
  }
}





Ternary operator on double value

public class Main {
  public static void main(String[] args) {
    
    double d = 5.0;
    d *= 4.0;
    System.out.println("d = " + d);
    System.out.println("Ternary: " + (d == 5 ? "yes" : "no"));
  }
}





Trigonometric Demo

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
public class TrigonometricDemo {
  public static void main(String[] args) {
    double degrees = 45.0;
    double radians = Math.toRadians(degrees);
    System.out.format("The value of pi is %.4f%n", Math.PI);
    System.out.format("The sine of %.1f degrees is %.4f%n", degrees, Math
        .sin(radians));
    System.out.format("The cosine of %.1f degrees is %.4f%n", degrees, Math
        .cos(radians));
    System.out.format("The tangent of %.1f degrees is %.4f%n", degrees, Math
        .tan(radians));
    System.out.format("The arcsine of %.4f is %.4f degrees %n", Math
        .sin(radians), Math.toDegrees(Math.asin(Math.sin(radians))));
    System.out.format("The arccosine of %.4f is %.4f degrees %n", Math
        .cos(radians), Math.toDegrees(Math.acos(Math.cos(radians))));
    System.out.format("The arctangent of %.4f is %.4f degrees %n", Math
        .tan(radians), Math.toDegrees(Math.atan(Math.tan(radians))));
  }
}





Use Double constructor to convert double primitive type to a Double object.

public class Main {
  public static void main(String[] args) {
    double d = 10.56;
    Double dObj = new Double(d);
    System.out.println(dObj);
  }
}





Use toString method of Double class to convert Double into String.

public class Main {
  public static void main(String[] args) {
    Double dObj = new Double(10.25);
    String str = dObj.toString();
    System.out.println(str);
  }
}