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?
A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale.
The value of the BigDecimal is (BigInteger/10**scale). A negative scale will result in a NumberFormatException.
In java, BigDecimal consists of a random precision integer scale and a 32-bit integer scale. If positive or zero, the scale is the number of digits to the right of the decimal point.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With