Which XML data type should I use for currency/money?

Zac Blazic picture Zac Blazic · Jun 23, 2011 · Viewed 15k times · Source

After reading a few questions on what Java data type to use for currency/money, I have decided to use the int/long method, where you store the value of the currency/money as its lowest unit (such as cents).

Does this apply to storing the data as well (in XML)?

The first thing that comes to my mind is no, because it will just be "parsed" into an XML decimal format when storing the data, and "parsed" back again when I read the data.

Any suggestions are welcome, as I am new to this.

Answer

Michael Kay picture Michael Kay · Jun 23, 2011

Hard to give you a design with so little input on requirements, but I would never put money amounts in XML without the currency:

<amount currency="GBP">230.45</amount>

But if you're in the US people may treat you like someone from outer space if you dare to suggest they handle multiple currencies, so your mileage may vary...

I think a good test of whether you've designed XML well is: will a human reader guess correctly what this means without reaching for the documentation? Not everyone shares that view of the requirements, and it's sometimes impractical. But omitting the decimal point is just asking for the data to be misprocessed somewhere along the line.