问题
With the following code:
BigDecimal x = new BigDecimal("34.5678");
BigDecimal a = x.movePointRight(3);
BigDecimal b = x.scaleByPowerOfTen(3);
BigDecimal c = x.movePointRight(-3);
BigDecimal d = x.scaleByPowerOfTen(-3);
a and b are both 34567.8 and c and d are both 0.0345678.
a.scale()
and b.scale
are both 1 and c.scale()
and d.scale()
are both 7.
In what circumstances do these two methods produce different results?
回答1:
movePointRight
will prevent a negative scale from occurring if it results in one.scaleByPowerOfTen
will not prevent this.
Example code:
import java.math.BigDecimal;
public class BigDecimalScale {
public static void main(String... args) {
long base = 12345;
int scale = 4;
BigDecimal number = BigDecimal.valueOf(base, scale);
System.out.println(number);
BigDecimal pointRight = number.movePointRight(5);
System.out.println(pointRight + "; my scale is " + pointRight.scale());
BigDecimal scaleBy = number.scaleByPowerOfTen(5);
System.out.println(scaleBy + "; my scale is " + scaleBy.scale());
}
}
Result:
1.2345
123450; my scale is 0
1.2345E+5; my scale is -1
回答2:
I've found the answer. If x is declared as
BigDecimal x = new BigDecimal("34.5678", new MathContext(4));
Then a has a scale of 0, but b has a scale of -1.
a.toString()
gives 34570, b.toString()
gives 3.457E+4
来源:https://stackoverflow.com/questions/25454734/what-is-the-difference-between-bigdecimal-movepointright-and-scalebypoweroften