日期:2014-05-20  浏览次数:20721 次

decimal primitive type

import java.math.BigDecimal;

public class Change {

    public static void main(String args[]) {

        System.out.println(new BigDecimal("2.00").

                           subtract(new BigDecimal("1.10")));

    }

}





This version is not terribly pretty, as Java provides no linguistic support for BigDecimal. Calculations with BigDecimal are also likely to be slower than those with any primitive type, which might be an issue for some programs that make heavy use of decimal calculations. It is of no consequence for most programs.

In summary, avoid float and double where exact answers are required; for monetary calculations, use int, long, or BigDecimal. For language designers, consider providing linguistic support for decimal arithmetic. One approach is to offer limited support for operator overloading, so that arithmetic operators can be made to work with numerical reference types, such as BigDecimal. Another approach is to provide a primitive decimal type, as did COBOL and PL/I.


考虑到浮点数的不精确性给许多计算应用带来麻烦,一种办法就是语言层面支持小数运算,而不像上面程序中那样,
如果说要让语言设计者考虑linguistic support for decimal arithmetic in java.
有哪些方法可供实现,利弊点?
因为文中提到用BigDecimal这种库对象方式不够完美(我猜可能是太heavy了)
但是如果实现小数运算的语言级支持,也就是primitive decimal type,是不是本质也是整形数的运算呢,那如果要再转成二进制是不是又有麻烦。

------解决方案--------------------
这个东西,我们真的很难说清。我其实也根本说不出个子丑寅卯来。我只是凭个人感觉,认为extends BigDecimal来得更可靠一些。而且,设计出来primitive decimal type,完善其功能后,可能未见得比extends BigDecimal好。

我不知道你的实质需求是什么。你看看这个对你有帮助么?
http://stackoverflow.com/questions/10060158/set-all-bigdecimal-operations-to-a-certain-precision

另外,我建议你尝试给欧美的一些学者email,他们都是非常友好的,而且考虑问题也会很全面,从他们那你可能会有满意答复。比如,就像你说的,“究竟是出于什么考虑而没有设计primitive decimal type”这样的问题。一旦某个人给你回信了,相信受益匪浅。
------解决方案--------------------
jdk1.7里面,也没有对这块改进,看来甲骨文是不想在这个类上下功夫了。
------解决方案--------------------
楼主读的是 Joshua Bloch, Neal Gafter 写的 Java? Puzzlers: Traps, Pitfalls, and Corner Cases
吧? 
这段话,原出处应是这本书。

与大家聊聊我的看法。

对于一种 data type, 要不要提供 primitive type 的支持?
相当程度上取决于,是否有 hardware 支持,从而取得 best performance.

因为 primitive type 多都是值运算,总是 copy, 所以 performance 很重要!

典型的例子是 int, 它在各种语言中都有很好的支持,因为,它是 natively supported by hardware. 它就是 cpu 的 register. float 也是,它有专门的 hardware unit 支持它的运算。

String 是反例,在 java 它是 “准primitive” ,language supported simple type. 在 C/C++ 里它不是。