0

Floating point is bad for storing currency values such as 3.33 or 3.10. Because performing math on floating point loses precision due, for example: 74.20+153.20==227.40 is TRUE in real life, but FALSE in R.

This Q&A thread talks about making a 'cents' field. Such that dollars_float 123.45 becomes cents_int 12345.

Why not use Double or Float to represent currency?

A solution that works in just about any language is to use integers instead, and count cents. For instance, 1025 would be $10.25. Several languages also have built-in types to deal with money. Among others, Java has the BigDecimal class, and C# has the decimal type.

How can we make an R class to store currency as an integer?

Would be a nice bonus if the class had a print method to automatically printed in a nice format like 2,222.22.

M.Viking
  • 5,067
  • 4
  • 17
  • 33

1 Answers1

0

Here is what I use to print floats as currency:

paste("$", round(number_i_want_as_currency, 2))

I use this at the very end of the calculations just before printing to minimize rounding errors. The only thing it is missing from your format request is the commas every three digits.

If you wanted to store the values I would recommend leaving out the paste("$"...) and just doing...

currency_storage <- round(number_i_want_as_currency, 2)
bstrain
  • 278
  • 1
  • 9
  • 1
    This is about losing precision due to floating point. eg `74.20+153.20==227.40` is `TRUE` in real life. – M.Viking Oct 03 '19 at 03:42
  • 1
    If you must store it as an integer then why not use cents_int as you described? If you want it to be formatted to look like currency AND evaluate to true you could use `as.numeric(format(74.20 + 153.20, nsmall = 2)) == 227.40` which is `TRUE` – bstrain Oct 03 '19 at 04:12
  • 1
    It'd probably make sense to define a new class for currency and then a `print.currency` method. That way you can transparently deal with the underlying values while having nice presentation of results. – thelatemail Oct 03 '19 at 04:15