Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Double Multiplication explanation? [duplicate]

Tags:

java

double

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

like image 994
DreamsOfHummus Avatar asked Jul 10 '13 13:07

DreamsOfHummus


People also ask

How do you multiply double in Java?

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.

What is double double in Java?

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.

What happens when you multiply an int by a double in Java?

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.

How do you multiply BigDecimal?

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.


1 Answers

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.

like image 50
Arnaud Denoyelle Avatar answered Nov 15 '22 17:11

Arnaud Denoyelle