I have a simple calculation that uses doubles but I\'m getting an unexpected result and I can\'t understand why?
import java.util.Scanner;
public class Versa
Doubles (floating-point values in general) cannot always represent exactly what we think of intuitively as a precise value. This is because of the way in which floats are stored, and can vary from machine to machine and language to language. When you try to store 2.99
, the actual value that is stored may be very slightly different (e.g. 2.990000000000002
). This question gives a decent, quick overview of why.
You should therefore (as it says through the link) never use floating-point primitives to represent currency. Either use BigDecimal
, or keep track of two integers yourself (e.g. int dollars;
and int cents;
).