From what I have read, numbers in JavaScript are actually stored as floating points and there is no real integer type. Is this accurate?
If there is no integer type, then how can I accurately store currencies? As a string or something?
From what I have read, numbers in JavaScript are actually stored as floating points and there is no real integer type. Is this accurate?
If there is no integer type, then how can I accurately store currencies? As a string or something?
[...] and there is no real integer type. Is this accurate?
Yes.
If there is no integer type, then how can I accurately store currencies?
You can still use values that we would consider as integers, i.e. 5
, 42
, etc. Those values are accurate. "Integer" values only lose precision if they are > 2^53.
What you should avoid, in any language, is using rational numbers to represent currency, if you perform any computation with it. Meaning, instead of 4.13
, you should use 413
.
To display as currency, toFixed
is a great method:
var someMoney = 123.1;
var formattedCurrency = someMoney.toFixed(2); //this is now the string "123.10"
console.log('$' + formattedCurrency);