DEV Community

Shahriyar Al Mustakim Mitul
Shahriyar Al Mustakim Mitul

Posted on

How to solve rounding error in Java, Python ?

What is the summation of

0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1 ?
Enter fullscreen mode Exit fullscreen mode

1.0 , right?
Let's add them in java:

test.java

public class test{
    //main method
    public static void main(String[] args) {
        System.out.println(0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1);

    }
}
Enter fullscreen mode Exit fullscreen mode

Output: 0.9999999999999999

In Python:

print(0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1)
Enter fullscreen mode Exit fullscreen mode

Output: 0.9999999999999999

now, assume that you have 100 taka 45 paisa . Other than taking it as float or double as data type, we should take integer data type.

so don't take

double balance=100.45
Enter fullscreen mode Exit fullscreen mode

Take this

int balance = 10045
Enter fullscreen mode Exit fullscreen mode

This is how you can solve this issue

Top comments (0)