这个问题在这里已有答案:
首先,我的搜索技能可能不如我所希望的那么好,所以也许这种问题已经存在 . 如果是这样请告诉我..
请参阅以下代码:
new BigDecimal("5").add(new BigDecimal("7"));
VS
new BigDecimal("5").add(new BigDecimal("7"), mathContext);
在哪种情况下我真的需要一个mathcontext( except divisions )?
除非我划分一些东西,否则我从不使用mathcontext . 据我所知,这总是有效,所以这里可能有什么缺点?在加,减,乘上需要mathcontext吗?我不太喜欢BigDecimal,我只是想用它来不丢失任何信息,比如使用双打时 . 因为我有时会在添加内容时看到带有mathcontext的代码,所以我太害怕只删除它只是因为我认为它是没用的...
我读到question但是没有't really find a proper answer to my specific question... I begin with BigDecimals without mathcontext and then calculate with them. So my question is, will I ever have drawbacks with this regarding information loss / precision etc? Or will this simply lead to maximum information and that'吗?
Edit: I don't want to round, never. In cases of a division like 1/3 I would have to, of course, but in the cases of add, multiply and subtract I don't want any rounding. Do I then need a mathcontext in any circumstance?
2 回答
如果你正在做数学运算,那就需要四舍五入 .
如果使用一些小数部分对两个数字进行加,减或相乘,并且想要对结果进行舍入,则还可以使用mathcontext .
If you don't need to round anything, then you don't need it.
所以它不仅限于避免无法休息的问题,如1/3的划分
我可以想象一种情况,你希望将结果舍入而de操作数不是 . 添加的一个例子 .
所以,也许你希望你的结果只有小数位,所以你会使用
MathContext
来制作它我不知道一个现实世界的例子,但我认为它们存在是不可想象的 .