float vs double data types in Java

By: Baski Emailed: 1768 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision. For example, calculations such as square root, or transcendentals such as sine and cosine, result in a value whose precision requires a floating-point type. Java implements the standard (IEEE–754) set of floatingpoint types and operators. There are two kinds of floating-point types, float and double, which represent single- and double-precision numbers, respectively. Their width and ranges are shown here:

 

Name Width in Bits Range
double 64 1 .7e–308 to 1.7e+308
float 32 3 .4e–038 to 3.4e+038

Each of these floating-point types is examined next.

float

The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on some processors and takes half as much space as double precision, but will become imprecise when the values are either very large or very small. Variables of type float are useful when you need a fractional component, but don't require a large degree of precision. For example, float can be useful when representing dollars and cents.

Here are some example float variable declarations:

float hightemp, lowtemp;

double

Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations. All transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values. When you need to maintain accuracy over many iterative calculations, or are manipulating large-valued numbers, double is the best choice.

Here is a short program that uses double variables to compute the area of a circle:

// Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area

System.out.println("Area of circle is " + a);


}


}


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(7)


1. View Comment

"For example, float can be useful when representing dollars and cents."

This is wrong. VERY wrong. You should never, under any circumstances, use a float to represent money.

It's better to use scaled integers or, failing that, BCD.


View Tutorial          By: David at 2009-10-08 13:47:08
2. View Comment

this is a very good artical about floating & double data types for us.

View Tutorial          By: Gayathri at 2012-10-31 12:19:28
3. View Comment

"For example, float can be useful when representing dollars and cents."

No.

Check "Learning the Java Language / Language Basics / Primitive Data Types" : "This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead."


View Tutorial          By: rangzen at 2014-03-28 09:31:47
4. View Comment

The Compleate Reference
JAVA Seventh Edition

Author :
Herbert Schildt


View Tutorial          By: joshap at 2014-10-25 12:05:41
5. View Comment

from docs api api/java/awt/Frame/setOpacity:

public void setOpacity(float opacity)
Sets the opacity of the window.
The opacity value is in the range [0..1]
//

commenting because if float isn't good for precision it's strange to me oracle would choose float for this value


View Tutorial          By: robert at 2014-12-12 07:48:59
6. View Comment

Hi Robert,

The precision statement applies to numbers that have a large number of digits on either or both sides of the decimal point. The range of the opacity value is 0 to 1, which granted, could contain a value that exceed the floats ability to precisely hold it, but you would never be able to tell the difference and I would be quite surprised to find that value ever used in iterative calculations. By turning it into a percentage it may be easier to see why. The opacity can be set from 0% to 100%. So if you want to change it from 64% to 63% for example, the float would be .63 and doesn't need any more precision than that as your eye would have great difficulty seeing any discernible difference beyond that. Even if you got really picky and wanted to be able to set your opacity to 63.937364 percent and for another object set it to 63.937365 you would #1 - never ever be able to tell the difference and #2 - you will still not have come even close to exceeding that precision for which the float is capable of holding.


View Tutorial          By: George at 2015-01-31 06:25:18
7. View Comment

Actually, the given accuracy just barely exceeds what is possible in a float. A float is stored as: 1 sign bit, 23 mantissa bits, 1 sign bit for the exponent, and 7 bits for the exponent value.

Since the largest value that can be stored in 23 bits is 8388608, two consecutive floats in this region are:

8380398/131072 = 63.93736267
8380399/131072 = 63.9373703

Meaning that it can just barely distinguish between 63.93736 and 63.93737, which is still MUCH better than the human eye!


View Tutorial          By: William Fraser at 2015-06-07 16:37:52

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Baski
Compiling multiple source files and specifying classpath using javac
The equals() Method example in Java
Default Values for Data Types in Java
JSP Example to connect to MS SQL database using Tomcat Connection Pool
<convertNumber> and <convertDateTime> in JSF
Enable/Disable Scripting Elements in JSP
Using calloc() Function in C
lseek() sample program in C
Arrays of Structures example program in C
The Basic Syntax Expression Language in JSP
Initialization of Pointer Arrays in C
Functions returning non-integer values in C
Increment and Decrement Operators in C
Getting Started with C
What is JSF (JavaServer Faces)?

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
InetAddress Example program in Java
Read from a COM port using Java program
Stack example in Java - push(), pop(), empty(), search()
How to use ArrayList in Java
The Basic Structure of a Simple Java program
Using StringTokenizer in Java
FileReader and FileWriter example program in Java
Transient vs Volatile modifiers in Java
Vector example in Java
Method Overriding in Java
Method Overloading (function overloading) in Java
instanceof sample program in Java
append() in Java
Student marks calculation program in Java
Reading from a file and writing to a file using Java program
Most Emailed Articles (in Java)
Text to Speech conversion program in Java
inheritance in Java
How to initialize an Array and how to copy the array
Using Charts in JasperReports
What is Unicode?
Operator Precedence in Java
Of Object, equals (), == and hashCode ()
DateFormat sample program in Java
A Simple whois program in Java
CharArrayReader example program in Java
ByteArrayOutputStream - sample program in Java
Vector example in Java
Arrays example in Java - asList(), binarySearch(), fill(), sort(), equals()
HashSet Sample program in Java
Disadvantages of using Native methods in Java