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
Leie is reply Vinicius
– Luiz Augusto
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.
– anonimo
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 Macedo
Vinicius, you can read more about this here and here.
– hkotsubo