Using double to temporarily store currency values?

This question already has an answer here:

  • Why not use Double or Float to represent currency? 14 answers

  • No, it still causes problems, even if you don't perform any calculations. The problem is that the value you store might not be exactly representable as a double , so even if you just store it and read it back, you might not get back what you stored.

    If you store 0.1 in a double , for instance, you'll find it's not actually 0.1 stored at all, because you can't represent 0.1 exactly in binary.


    No. A double is never the correct type to store a currency value. Doubles are floating point values, that is, they are basically numbers of the form x * 2^y, where x and y are integers. Thus, some values, such as 0.10 (10 cents) have no exact representation as a double.


    The problem here is that when you save say 10.12 in a double variable it may not have a exact double representation, so the java runtime will save it as a closest possible double representation, say 10.1199999999999 or 10.1200000000001 (just an example, I am not sure, have to test). So you get the point, as soon as you put the value in a double variable the currency value is approximated. However, that being said, you can still use a double for calculations and then use appropriate formatting while printing out the values or writing to file, such that the non-significant digits are hidden, depending on your application.

    链接地址: http://www.djcxy.com/p/85814.html

    上一篇: 为什么java将整数转化为更少的东西

    下一篇: 使用double来临时存储货币值?