synthetic
synthetic

Reputation: 908

What is the best format/type for money in JSON API

Basically I am considering floating point number or string.

Strings:

"10.00"
"10.05"
"10.50"
"1,000"

Floating point number

10
10.05
10.5
1000

I like the formatting of Strings and there could be an issue with floating point number limited precision.

What would you choose and why?

Upvotes: 5

Views: 2562

Answers (2)

Mattias Nilsson
Mattias Nilsson

Reputation: 3767

You should never use float/double for money. The reason is that they don't do what you want them to when dealing with money.

Simple example where I get 10 cents, then I get another 10 cents and then I buy something for 20 cents. How much is left? (using the interactive python prompt to illustrate)

>>> 0.1 + 0.1 - 0.2 == 0
True

Now let's try the same thing with 3 dimes and buying something for 30 cents:

>>> 0.1 + 0.1 + 0.1 - 0.3 == 0
False

The reason is of course that the float/double types can not exactly represent all values. When you manipulate the numbers, you might accumulate the errors so that it actually becomes noticeable. All programming languages that use float/double have this problem to some extent.

You'll end up fixing bugs by implementing functions called "isAlmostZero" and "isCloseTo" or some other silliness. And yes, I've been working with a system like that.

This link also has some explanations about what float/double is a bad idea.

Now, if you can put them as a float in JSON and not translate them into float/double in your programming language, it might be OK, but then you're still not using the float/double as datatype, just something that looks like it and translates into something different. I suppose most JSON parsers will just turn it into a floating point value if you enter it that way.

Upvotes: 9

Kirkova
Kirkova

Reputation: 347

Use floats. Money is a number, so it will make more sense to use a number to represent it. And precision shouldn't be an issue since "Floating point numbers are usually implemented using double in C" which means there won't be any rounding issues between $0.00 - $0.99

Resources: https://docs.python.org/2/library/stdtypes.html

Upvotes: -4

Related Questions