Java Tutorial/Data Type/Float
Содержание
- 1 Check if a string is a valid number
- 2 Compares two floats for order.
- 3 Compare Two Java float Arrays
- 4 Convert from float to String
- 5 Convert from String to float
- 6 Converting a String to a float type Number
- 7 Convert Java Float to Numeric Primitive Data Types
- 8 Convert Java String to Float Object
- 9 Declaring a variable of type float
- 10 Declaring more than one float variable in a single statement
- 11 Floating�Point Types
- 12 For a float value x, this method returns +f x >= 0 and -f Returns NaN if x is NaN.
- 13 Java Float Comparison
- 14 Java float is 32 bit single precision type and used when fractional precision calculation is required.
- 15 Java Float isInfinite Method
- 16 Java Float isNaN Method
- 17 Java Float Wrapper Class
- 18 Min and Max values of data type float
- 19 Pass floats as string literals to a method
- 20 Tests two float arrays for equality.
- 21 Use Float constructor to convert float primitive type to a Float object.
- 22 Use Float.valueOf to convert string value to float
- 23 Use System.out.printf to format float point number
- 24 Use toString method of Float class to convert Float into String.
Check if a string is a valid number
<source lang="java">
public class Main {
public static void main(String[] argv) throws Exception { String age = "1"; String height = "1.5"; String weight = "5.9"; int theAge = Integer.parseInt(age); float theHeight = Float.parseFloat(height); double theWeight = Double.parseDouble(weight); System.out.println("Age: " + theAge); System.out.println("Height: " + theHeight); System.out.println("Weight: " + theWeight); }
}</source>
Compares two floats for order.
<source lang="java">
import java.math.BigDecimal; import java.math.BigInteger; /**
* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
/**
* Provides extra functionality for Java Number classes. * * @author * @author Eric Pugh * @author Phil Steitz * @since 1.0 * @version $Id: NumberUtils.java 488819 2006-12-19 21:50:04Z bayard $ * */
public class Main {
/** * Compares two floats for order. * * This method is more comprehensive than the standard Java greater than, * less than and equals operators.*
-
*
- It returns
-1
if the first value is less than the second. * - It returns
+1
if the first value is greater than the second. * - It returns
0
if the values are equal. *
* * The ordering is as follows, largest to smallest:*
-
*
- NaN *
- Positive infinity *
- Maximum float *
- Normal positive numbers *
- +0.0 *
- -0.0 *
- Normal negative numbers *
- Minimum float (-Float.MAX_VALUE) *
- Negative infinity *
* * ComparingNaN
withNaN
will return *0
. * * @param lhs the firstfloat
* @param rhs the secondfloat
* @return-1
if lhs is less,+1
if greater, *0
if equal to rhs */ public static int compare(float lhs, float rhs) { if (lhs < rhs) { return -1; } if (lhs > rhs) { return +1; } //Need to compare bits to handle 0.0 == -0.0 being true // compare should put -0.0 < +0.0 // Two NaNs are also == for compare purposes // where NaN == NaN is false int lhsBits = Float.floatToIntBits(lhs); int rhsBits = Float.floatToIntBits(rhs); if (lhsBits == rhsBits) { return 0; } //Something exotic! A comparison to NaN or 0.0 vs -0.0 //Fortunately NaN"s int is > than everything else //Also negzeros bits < poszero //NAN: 2143289344 //MAX: 2139095039 //NEGZERO: -2147483648 if (lhsBits < rhsBits) { return -1; } else { return +1; } }
}</source>
Compare Two Java float Arrays
<source lang="java">
import java.util.Arrays; public class Main {
public static void main(String[] args) { float[] a1 = new float[] { 4.4f, 3.3f, 5.3f }; float[] a2 = new float[] { 4.4f, 3.3f, 5.3f }; System.out.println(Arrays.equals(a1, a2)); }
}</source>
Convert from float to String
<source lang="java">
public class Main {
public static void main(String[] args) throws Exception { String str = Float.toString(0.3F); }
}</source>
Convert from String to float
<source lang="java">
public class Main {
public static void main(String[] args) throws Exception { Float f = Float.valueOf("0.2").floatValue(); }
}</source>
Converting a String to a float type Number
<source lang="java">
public class Main {
public static void main(String[] argv) throws Exception { float f = Float.parseFloat("123.4"); System.out.println(f); }
}</source>
Convert Java Float to Numeric Primitive Data Types
<source lang="java">
public class Main {
public static void main(String[] args) { Float fObj = new Float("10.50"); byte b = fObj.byteValue(); System.out.println(b); short s = fObj.shortValue(); System.out.println(s); int i = fObj.intValue(); System.out.println(i); float f = fObj.floatValue(); System.out.println(f); double d = fObj.doubleValue(); System.out.println(d); }
}</source>
Convert Java String to Float Object
<source lang="java">
public class Main {
public static void main(String[] args) { Float fObj1 = new Float("10.64"); System.out.println(fObj1); Float fObj2 = Float.valueOf("10.76"); System.out.println(fObj2); float f = Float.parseFloat("7.39"); System.out.println(f); }
} /* 10.64 10.76 7.39
- /</source>
Declaring a variable of type float
<source lang="java">
public class MainClass{
public static void main(String[] arg){ float f1 = 9E-28F; System.out.println(f1); }
}</source>
9.0E-28
Declaring more than one float variable in a single statement
<source lang="java">
public class MainClass {
public static void main(String[] arg) { float f1 = 185.2F, f2 = 108.5F; System.out.println(f1); System.out.println(f2); }
}</source>
185.2 108.5
Floating�Point Types
<source lang="java">
public class Main {
public static void main(String[] args) { double pi = 3.14159; float f = 2.2F; System.out.println("pi = " + pi); System.out.println("f = " + f); int n = 15, d = 4; f = n / d; System.out.println("15/4 = " + f); int radius = 10; double area = pi * radius * radius; System.out.println("area = " + area); }
}</source>
For a float value x, this method returns +f x >= 0 and -f Returns NaN if x is NaN.
<source lang="java">
import java.io.File; /*
* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */
public class Main {
/** * For a float value x, this method returns +1.0F if x >= 0 and -1.0F if x < * 0. ReturnsNaN
ifx
isNaN
. * * @param x the value, a float * @return +1.0F or -1.0F, depending on the sign of x */ public static float indicator(final float x) { if (Float.isNaN(x)) { return Float.NaN; } return (x >= 0.0F) ? 1.0F : -1.0F; }
}</source>
Java Float Comparison
<source lang="java">
public class Main {
public static void main(String[] args) { float f1 = 5.5f; float f2 = 5.4f; int i1 = Float.rupare(f1, f2); if (i1 > 0) { System.out.println(">"); } else if (i1 < 0) { System.out.println("<"); } else { System.out.println("="); } Float fObj1 = new Float("5.5"); Float fObj2 = new Float("5.4"); int i2 = fObj1.rupareTo(fObj2); if (i2 > 0) { System.out.println(">"); } else if (i2 < 0) { System.out.println("<"); } else { System.out.println("="); } }
}</source>
Java float is 32 bit single precision type and used when fractional precision calculation is required.
<source lang="java">
public class Main {
public static void main(String[] args) { float f = 12.3f; System.out.println("Value of float variable f is :" + f); }
} //Value of float variable f is :12.3</source>
Java Float isInfinite Method
<source lang="java">
public class Main {
public static void main(String[] args) { float f = (float) 1 / 0; boolean b1 = Float.isInfinite(f); System.out.println(b1); Float fObj = new Float(f); boolean b2 = fObj.isInfinite(); System.out.println(b2); }
}</source>
Java Float isNaN Method
<source lang="java">
public class Main {
public static void main(String[] args) { float f = (float) Math.sqrt(-10); boolean b1 = Float.isNaN(f); System.out.println(b1); Float fObj = new Float(f); boolean b2 = fObj.isNaN(); System.out.println(b2); }
}</source>
Java Float Wrapper Class
<source lang="java">
public class Main {
public static void main(String[] args) { float f = 10.10f; Float fObj1 = new Float(f); System.out.println(fObj1); double d = 10.10; Float fObj2 = new Float(d); System.out.println(fObj2); Float fObj3 = new Float("25.34"); System.out.println(fObj3); }
}</source>
Min and Max values of data type float
<source lang="java">
public class Main {
public static void main(String[] args) { System.out.println(Float.MIN_VALUE); System.out.println(Float.MAX_VALUE); }
} /* 1.4E-45 3.4028235E38
- /</source>
Pass floats as string literals to a method
<source lang="java">
public class Main {
public static void main(String[] argv) { System.out.println(0.1f); }
}</source>
Tests two float arrays for equality.
<source lang="java">
import java.util.Arrays; /*
* JCommon : a free general purpose class library for the Java(tm) platform * * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------- * ArrayUtilities.java * ------------------- * (C) Copyright 2003-2005, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ArrayUtilities.java,v 1.7 2008/09/10 09:21:30 mungady Exp $ * * Changes * ------- * 21-Aug-2003 : Version 1 (DG); * 04-Oct-2004 : Renamed ArrayUtils --> ArrayUtilities (DG); * */
public class Main {
/** * Tests two float arrays for equality. * * @param array1 the first array (null
permitted). * @param array2 the second arrray (null
permitted). * * @return A boolean. */ public static boolean equal(final float[][] array1, final float[][] array2) { if (array1 == null) { return (array2 == null); } if (array2 == null) { return false; } if (array1.length != array2.length) { return false; } for (int i = 0; i < array1.length; i++) { if (!Arrays.equals(array1[i], array2[i])) { return false; } } return true; }
}</source>
Use Float constructor to convert float primitive type to a Float object.
<source lang="java">
public class Main {
public static void main(String[] args) { float f = 10.56f; Float fObj = new Float(f); System.out.println(fObj); }
}</source>
Use Float.valueOf to convert string value to float
<source lang="java">
/*
* 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 ValueOfDemo {
public static void main(String[] args) { // this program requires two arguments on the command line if (args.length == 2) { // convert strings to numbers float a = (Float.valueOf(args[0])).floatValue(); float b = (Float.valueOf(args[1])).floatValue(); // do some arithmetic System.out.println("a + b = " + (a + b)); System.out.println("a - b = " + (a - b)); System.out.println("a * b = " + (a * b)); System.out.println("a / b = " + (a / b)); System.out.println("a % b = " + (a % b)); } else { System.out.println("This program requires two command-line arguments."); } }
}</source>
Use System.out.printf to format float point number
<source lang="java">
/*
* 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 ExponentialDemo {
public static void main(String[] args) { double x = 11.635; double y = 2.76; System.out.printf("The value of e is %.4f%n", Math.E); System.out.printf("exp(%.3f) is %.3f%n", x, Math.exp(x)); System.out.printf("log(%.3f) is %.3f%n", x, Math.log(x)); System.out.printf("pow(%.3f, %.3f) is %.3f%n", x, y, Math.pow(x, y)); System.out.printf("sqrt(%.3f) is %.3f%n", x, Math.sqrt(x)); }
}</source>
Use toString method of Float class to convert Float into String.
<source lang="java">
public class Main {
public static void main(String[] args) { Float fObj = new Float(10.25); String str = fObj.toString(); System.out.println(str); }
}</source>