5

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?

j08691
  • 204,283
  • 31
  • 260
  • 272
timbram
  • 1,797
  • 5
  • 28
  • 49

2 Answers2

15

[...] 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.

See Why not use Double or Float to represent currency?

George Stocker
  • 57,289
  • 29
  • 176
  • 237
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    Thank you! That helps me out a lot and makes more sense! So, you are saying that if I wanted to store $9.99 then I would do best to store it as 999 and the divide by 100 after I retrieve it? – timbram Apr 13 '15 at 18:54
  • 1
    Yes! Store monetary values in the smallest unit (e.g. pennies). – Felix Kling Apr 13 '15 at 18:55
  • 2
    You should store it as 999, manipulate it as 999 and turn it into 9.99 only when you display it. – Tony Edgecombe Mar 26 '17 at 16:15
  • Ok, so I want to store monetary values as pennies. But to get it to pennies from dollars there is still that multiplication by 100 which needs to happen. It seems unavoidable if you want to take a user's input and convert it to pennies. – papiro Jun 12 '19 at 16:54
  • Check [this](https://frontstuff.io/how-to-handle-monetary-values-in-javascript) out. Briefs on how to and how not to handle money in JS and other languages – Kwesi Smart Oct 10 '19 at 11:05
-4

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);
KJ Price
  • 5,774
  • 3
  • 21
  • 34
  • @DougCoburn Perhaps I misunderstood you, but the code you provided should absolutely be 1.25 and 1.00. I think you should check your math again or else I would appreciate another explanation of the issue here. The OP asked about how to store currencies, that is exactly what my code does. – KJ Price Jun 11 '17 at 22:13