Why is using a NON-decimal data type bad for money?

前端 未结 5 1622
执念已碎
执念已碎 2021-02-08 23:13

tl;dr: What\'s wrong with my Cur (currency) structure?

tl;dr 2: Read the rest of the question please, before giving an

5条回答
  •  北海茫月
    2021-02-08 23:37

    Mehrdad, I don't think I could convince you if I brought in the entire SEC. Now, your entire class basically implements BigInteger arithmetic with an implied shift of 2 decimal places. (It should be at least 4 for accounting purposes, but we can change 2 to 4 easily enough.)

    What advantage do we have backing this class with double instead of BigDecimal (or longlong if something like that is available)? For the advantage of a primitive type I pay with expensive rounding operations. And I also pay with inaccuracies. [Example from here 1]

    import java.text.*;
    
    public class CantAdd {
       public static void main(String[] args) {
          float a = 8250325.12f;
          float b = 4321456.31f;
          float c = a + b;
          System.out.println(NumberFormat.getCurrencyInstance().format(c));
       }
    }
    

    OK, here we backed with a float instead of a double, but shouldn't that be a BIG warning flag that the whole concept is wrong and that we may get in trouble if we have to make millions of calculations?

    Every professional who works in finance believes that floating-point representation of money are a bad idea. (See, among dozens of hits, http://discuss.joelonsoftware.com/default.asp?design.4.346343.29.) Which is more likely: they are all stupid, or floating-point money is indeed a bad idea?

提交回复
热议问题