Can float and double value represent decimal number exactly?
The int and long type do represent integral numbers exactly, but the value of float and double type do not represent decimal numbers exactly.
The float and double perform binary floating-point arithmetic. It only provide approximate of the results of arithmetic operations because they are binary and cannot exactly represent negative powers of then (i.e., 10 -1); If you want an exact representation you can use the java.math.BigDecimal class. For example,
import java.math.BigDecimal;
public class Change {
public static void main(String args[]) {
BigDecimal bigD1 = new BigDecimal("2.00");
BigDecimal bigD2 = new BigDecimal("1.10");
System.out.println(bigD1.subtract(bigD2));
}
}
Note that BigDecimals are String-based
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- What are class variables in Java?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?
- How to Use JDBC Java to Create Table?
- Why final variable in Enhanced for Loop does not act final?