I am using Googles protocol buffer library within my persistent storage system and want to persist currency values, but I am not sure that the floating point types provided by photo (float/double) are good enough. Are there any downsides to storing all of my currency values as strings (e.g. storing "0.10" instead of 0.1), then using the Convert.ToDecimal function when I retrieve my data and need to do arithmetic?
-
2representation differences – Mitch Wheat Jul 25 '16 at 02:18
-
Also require much more memory to process than it should. – Lex Li Jul 25 '16 at 02:38
1 Answers
You are correct in anticipating that float/double
data types are not suitable for "currency!"
Consider how SQL databases (and, uhh, COBOL
programs ...) commonly store "currency" values: they use a decimal representation of some sort. For instance, a true COBOL
program might use a "binary-coded decimal (BCD)" data type. A Microsoft Access database uses a "scaled integer": the dollars-and-cents value multiplied by 10,000, giving a fixed(!) "4 digits to the right of the decimal."
For the immediate purposes of this question, I would definitely store the values as strings, and then give very serious thought to the number of digits to be stored and just how to handle "rounding" to that number of digits. (For instance, there are algorithms such as “banker’s rounding.”)
“Storage size?” You don’t care about that. What you do care about is, that if a particular customer (or, auditor ...) actually adds-up all the numbers on a printed statement, the bottom-line on that piece of paper will agree ... at the very(!) least, within a single penny.

- 8,490
- 5
- 28
- 41
-
Purely as a matter of interest, IBM's POWER CPUs have a decimal math coprocessor these days. Very handy for financial applications, gives a big speedup. And surprise surprise, IBM sell a lot of mainframes into the financial world! – bazza Oct 03 '16 at 21:32