As @Doug notes, floating point imprecision makes double
unsuitable for storing currency (or any other decimal values that require consistency), particularly if you want to do any math on these stored values.
While your solution to use String
type to store decimals will work, it might cause issues if performing math later.
One alternative is to store currency as int
'cents', then divide by 100 when displaying to the user – and thus multiple by 100 before storing user input.
For example, although as double
floats:
print(0.2 + 0.1);
= 0.30000000000000004
Instead as int
x 100:
int x = 20;
int y = 10;
print((x+y)/100);
= 0.3
This might get unwieldy if your project makes use of many different currency fields, but for most things there's a certain simplicity and transparency to using int
x100 for base-100 currencies that I think keeps code predictable.