[英]What is the difference between BigDecimal movePointRight and scaleByPowerOfTen?
使用以下代碼:
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和b均為34567.8,c和d均為0.0345678。 a.scale()
和b.scale
都是1, c.scale()
和d.scale()
都是7。
這兩種方法在什么情況下產生不同的結果?
movePointRight
將防止出現負面比例,如果它導致一個。 scaleByPowerOfTen
不會阻止這種情況。 示例代碼:
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());
}
}
結果:
1.2345
123450; my scale is 0
1.2345E+5; my scale is -1
我找到了答案。 如果x被聲明為
BigDecimal x = new BigDecimal("34.5678", new MathContext(4));
然后a的標度為0,但b的標度為-1。 a.toString()
給出34570, b.toString()
給出3.457E + 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.