// Reason 16 decimals ->> Output: 11
double num1 = 10.9999999999999999;
Integer res1 = (int) Math.floor(num1);
System.out.println(res1);
// Reason 15 decimals ->> Output: 10
double num2 = 10.999999999999999;
Integer res2 = (int) Math.floor(num2);
System.out.println(res2);
// Can you get 10 in both cases?
Anonymous #11493846
Level 3
Why does this happen in Java? With two equal numbers
Comments (1)
- Popular
- New
- Old
You must be signed in to leave a comment
Mark Team Lead
6 June 2024, 08:03
To get the output `10` in both cases, we need to understand how floating-point precision and rounding work in Java.
When dealing with floating-point numbers, the precision is limited, which can lead to unexpected results. The `double` type in Java follows the IEEE 754 standard for floating-point arithmetic, which means it can only accurately represent a certain number of decimal places. The numbers you provided have 16 and 15 decimal places respectively, which causes issues due to precision limits.
To ensure both cases output `10`, you can use the `BigDecimal` class in Java. `BigDecimal` provides arbitrary-precision arithmetic and can handle very large and very small floating-point numbers with great accuracy. You can use `BigDecimal` to perform the floor operation.
Here's the modified code to achieve this:
In this code:
1. `BigDecimal` is used to create a floating-point number with high precision.
2. `setScale(0, RoundingMode.FLOOR)` is used to scale the number to 0 decimal places, effectively performing the floor operation.
3.intValue() converts the resulting `BigDecimal` to an integer.
0