1

We have a highly complex financial model app that involves money & percentages. It's written in C# and we use its decimal type to represent both. It works fine, but we're trying to migrate the app to Java to get away from Microsoft.

I'm surprised to not find any Java native type to store money & percentages that provides both:

  1. Lossless precision
  2. Native style of doing calculations (e.g. using + for additions instead of .add())

I know the consensus is to use BigDecimal. That solves the storage part but it's very cumbersome to do calculations with it. For example instead of this with decimal:

((a + b + c + d) / e) * f

I'd have to do this with BigDecimal:

a.add(b).add(c).add(d).divide(e).multiply(f)

This is fine for a small amount of calculations, but we have thousands of calculations, some of their formulae are tens of lines. This quickly becomes unwieldy and hard to read.

Basically I'm looking for the exact replica of C#'s decimal type in Java.

Ascendant
  • 2,430
  • 3
  • 26
  • 34
  • 1
    Option 1: Suck it up. Java doesn't support operator overloading. Option 2: Use a different JVM language that does support operator overloading. kotlin or [Manifold](http://manifold.systems/) are two such. Best of luck! – Elliott Frisch Jun 17 '23 at 16:44
  • 1
    It seems unreasonable to suppose that an “exact replica” exists: what’s the exact replica of [inner classes](https://stackoverflow.com/q/2367015/8586227) in C#? – Davis Herring Jun 17 '23 at 16:48

3 Answers3

1

I find BigDecimal to be the best option and even used in multiple FinTech products for monitory calculations, yes correct it is really cumbersome to do calculations like ((a + b + c + d) / e) * f, to over come this limitation I have written some static factory methods like BigDecimal add( BigDecimal b1, BigDecimal b2) or using java varargs for adding multiple Big Decimals, in that case you can call add(a,b,c,d), similarly I have written methods for division, subtraction etc.

1

Unlike for example in Kotlin, it is not possible in Java as this language allows neither operator overloading nor infix functions.

You have to pick one:

  1. double: Keep readability and lose precision.
  2. Bigdecimal: Keep precision and lose readability.

If you manage to switch to Kotlin, you can use the power the BigDecimal Kotlin extension.

Thiyagu
  • 17,362
  • 5
  • 42
  • 79
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
0

On 2.), this isn't possible in Java as you're essentially wanting to overload arithmetic operators for some custom currency type.BigDecimal is the only way you can reliably achieve this.

TypeMonkey
  • 25
  • 3