2

I have seen there are issues when creating BigDecimal from double.

Although FastMoney doesn't use BigDecimal (as opposed to Money), I am not sure how either of them will behave when I crate them from a double value.

Is creating a FastMoney/Money instance from a double not recommended? Should I always try to create them from String?

Michel Feinstein
  • 13,416
  • 16
  • 91
  • 173

1 Answers1

1

double and especially float types are dangerous. This numbers are base-2 numeral system then it's not possible to represent 0.24F directly as the same it's not possible to represent 1/3 in decimal system without recurring decimal period i.e. 1/3=0.3333... or 0.(3).

So the float number 0.24F when printed back to decimal representation is shown as 0.23 with a change due to rounding:

println(0.24F) => 0.23999999463558197021484375

while 0.25F can be shown directly:

println(0.25F) => 0.25

So answering to your question: it depends. For 0.25, 0.5, 0.75 it's ok to use double.

But the FastMoney class uses not a floating-point arithmetic but a fixed-point arithmetic

Sergey Ponomarev
  • 2,947
  • 1
  • 33
  • 43