What to do with Java BigDecimal performance?

后端 未结 20 2480
陌清茗
陌清茗 2020-11-29 17:28

I write currency trading applications for living, so I have to work with monetary values (it\'s a shame that Java still doesn\'t have decimal float type and has nothing to s

20条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 18:16

    Assuming you can work to some arbitrary but known precision (say a billionth of a cent) and have a known maximum value you need handle (a trillion trillion dollars?) you can write a class which stores that value as an integer number of billionths of a cent. You'll need two longs to represent it. That should be maybe ten times as slow as using double; about a hundred times as fast as BigDecimal.

    Most of the operations are just performing the operation on each part and renormalizing. Division is slightly more complicated, but not much.

    EDIT:In response to the comment. You will need to implement a bitshift operation on your class (easy as along as the multiplier for the high long is a power of two). To do division shift the divisor until it's not quite bigger than the dividend; subtract shifted divisor from dividend and increment the result (with appropriate shift). Repeat.

    EDIT AGAIN:You may find BigInteger does what you need here.

提交回复
热议问题