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

如何获取BigDecimal的负数
比如有一个BigDecimal的对象decimal,按照正常思维是只要-decimal就可以了,但是java好像不支持这种写法。记得java好像不支持有符号数,求各位大神帮忙解决下这个难题

------解决方案--------------------
new BigDecimal("-"+decimal.toString())
------解决方案--------------------
简单数值类型才支持+-*/
BigDecimal是对象类型,要通过相应的方法来计算
for example
Java code
BigDecimal decimal = new BigDecimal(123);
decimal = decimal.multiply(new BigDecimal(-1));
System.out.println(decimal);

------解决方案--------------------
不看文档

public BigDecimal negate()
Returns a BigDecimal whose value is (-this), and whose scale is this.scale().

public BigDecimal negate(MathContext mc)
Returns a BigDecimal whose value is (-this), with rounding according to the context settings.
Parameters: mc - the context to use.
Returns: -this, rounded as necessary.
Throws: ArithmeticException - if the result is inexact but the rounding mode is UNNECESSARY.