0

If I have to design, say, a financial application that uses rational numbers (i.e., numbers with a fractional component), what datatype should I use for internally doing calculations?

I have two options:

  1. Use BigInt (BigInteger in Java) and emulate fixed point arithmetic. I have to keep track of the decimal point separately.

  2. Use BigDecimal and floating point arithmetic. BigDecimal is already a wrapper over BigInt that does most of what I need to do for 1.

I am inclined to use BigDecimal (approach 2) unless someone can give strong arguments for integer arithmetic.

EDIT: In relation to the linked question, I want to know which out of BigDecimal or BigInteger is better, while the other question is more generic and talks about the "best datatype" (which may or may not be out of the two above). In my case, my choice is limited to the two so I cannot use Currency type.

Jus12
  • 17,824
  • 28
  • 99
  • 157
  • BigDecimal should be fine :) – Ramesh Maharjan Nov 04 '17 at 09:02
  • Go for `BigDecimal`. Even though you wouldn't need it right now, it is future-proof when your app will expand new features. – Yassin Hajaj Nov 04 '17 at 09:03
  • Well, if it's possible, calculate in cents, not dollars. Then you can use simple integers or long integers and format the output lately. Maybe in a trading application performance will become an issue. – atmin Nov 04 '17 at 09:13
  • @YassinHajaj Could you elaborate a bit more what problems I could run into in future with `BigInteger`? – Jus12 Nov 04 '17 at 09:29
  • @Oleg edited the question to explain why it may not be a duplicate. – Jus12 Nov 04 '17 at 09:31
  • Integers can be used if you need precision of up to a cent, then you can just increment everything by 100. If in your case you need up to 18 decimals how are you planning on using `BigInteger`? – Oleg Nov 04 '17 at 09:37
  • Of course you *could* use BigIntegers, but if you need 18 decimals, a Bigdecimal is the best choice. After all, a BigDecimal is generally a scaled BigInteger (or long, depending on the values used). – Rudy Velthuis Nov 04 '17 at 10:57

0 Answers0