Counting the unwanted part in a double data type

I have a strange problem with the data type: double.

Here is my code:

public class Example { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub double a = 1.0; for(int i =0; i<10;i++){ System.out.println("Number => " + a ); a += 0.1; } } } 

The output should be:

 Number => 1.0 Number => 1.1 Number => 1.2 Number => 1.3 Number => 1.4 Number => 1.5 Number => 1.6 Number => 1.7 Number => 1.8 Number => 1.9 

But this example result code:

 Number => 1.0 Number => 1.1 Number => 1.2000000000000002 Number => 1.3000000000000003 Number => 1.4000000000000004 Number => 1.5000000000000004 Number => 1.6000000000000005 Number => 1.7000000000000006 Number => 1.8000000000000007 Number => 1.9000000000000008 

I am using eclipse to compile this code. I tried this on netbeans but nothing has changed.

How is this supposed to happen? Any ideas?

Hello

+4
source share
2 answers

It's not so easy. I would use Commons-Math

 for (int i = 0; i < 10; i++) { a = Precision.round(a, 1); // <- round to 1 digit after decimal point ... 

I think the only alternative to Java SE is

 a = Double.parseDouble(String.format(Locale.US, "%.1f", a)); 
+1
source

According to javadoc

If at least one of the operands to a numerical operator is of type double, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type double. If the other operand is not a double, it is first widened (ยง5.1.5) to type double by numeric promotion (ยง5.6).

Here is the source

0
source

Source: https://habr.com/ru/post/1483598/


All Articles