I recently tested something out that I heard using the following code
public static void main(String[] args) {
double x = 4.35 * 100;
System.out.println(x);
}
.
I am interested as to why this produces 434.99999999999994 rather than 435.0 . Thanks
The multiplication operator * and the “multiplyExact()” method can be used to multiply two values in java. The multiplication operator performs multiplication on any numeric value such as int, float, or double. The multiplyExact() method deals with only integer and double type values.
Double doubleValue() method in Java with examples The doubleValue() method of Double class is a built in method to return the value specified by the calling object as double after type casting.
When one operand is an int and the other is a double, Java creates a new temporary value that is the double version of the int operand. For example, suppose that we are adding dd + ii where ii is an int variable. Suppose the value of ii is 3. Java creates a temporary value 3.0 that is the corresponding double value.
multiply(BigDecimal multiplicand) is an inbuilt method in java that returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this. scale() + multiplicand.
When you type:
double x = 4.35;
x
is not stored as-is. It is stored in a approaching form (probably 4.349999999 in this case).
If you want exact result, please use BigDecimal
.
You can learn about the accuracy problems of floating-point technology.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With