Java Beginner Doubt - Why is the result of the double variable wrong?

Asked

Viewed 411 times

0

I made an algorithm that simulates a bank account, where the client can withdraw and deposit values, worked perfectly when I used variables like int, but when I use double type variables (in order for the algorithm to do bills with pennies) it returns some values that I think are wrong, for example:

public static void main(String[] args) {
    double valor1 = 10;
    double valor2 = 9.8;
    double resultado = valor1 - valor2;

    System.out.println(resultado);

The value he returns to me is 0.1999999999999993, when I think the right one would be 0.2

  • 1

    Leie is reply Vinicius

  • A floating point variable, according to IEEE 754-2008, is inherently inaccurate. If your application requires precision then don’t use this type of data. Only use it if your application can live with approximations within a margin of error.

  • What kind of data should I use for an algorithm that can add and subtract decimal numbers precisely? For example R$: 20.00 - R$ 19.90?

  • Vinicius, you can read more about this here and here.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.