Search code examples
jsongraphqldataformat

Should I use Ints for monetary values in GraphQL?


I know that I should use integers for "money values" when programming. I know it's because of the 0.1 + 0.2 != 0.3 problem. But I don't know the problem well enough to know if that's a problem in data formats (like JSON) as well.

In my concrete case: should I define

type Money {
    amount: Float!
    # ...
}

or

type Money {
    amount: Int!
    # ...
}

in GraphQL?


Solution

  • GraphQL itself does not perform any comparisons between resolved values. You might introduce sorting logic or something else that would require you to compare two floating point values, but this would be logic you implement yourself and so you could act accordingly. As such, the decision whether to use Float or Int should be based on the needs of clients consuming the API (or possibly other limitations like the language or database you're using on the backend) -- there are no additional considerations just because you're dealing with GraphQL.

    Similarly, there's nothing about serializing or deserializing JSON that would require floating point values to be compared.

    The JSON specification does not limit the size of numbers. As such, you technically might hit some language-specific limit when deserializing JSON, whether it's an integer or a floating point. But if you're working with currencies I'm guessing that's highly unlikely (for example, in JavaScript, the largest possible integer value is 9,007,199,254,740,991 versus the $100,000,000,000,000 or so in circulation of all currencies in the world.