比對 Java 中的 BigDecimal movePointRight 和 scaleByPowerOfTen
java.math.BigDecimal.movePointRight(int n) 返回一個 BigDecimal,它等效於小數點向右移動 n 位後的 BigDecimal。如果 n 為非負值,則呼叫僅從標度減去 n。
java.math.BigDecimal.scaleByPowerOfTen(int n) 返回一個數值等於 (this * 10n) 的 BigDecimal。結果的標度為 (this.scale() - n)。
以下是一個同時展示這兩種方法使用的示例 −
示例
import java.math.BigDecimal; public class Demo { public static void main(String... args) { long base = 3676; int scale = 5; BigDecimal d = BigDecimal.valueOf(base, scale); System.out.println("Value = "+d); System.out.println("
Demonstrating moveRight()..."); BigDecimal moveRight = d.movePointRight(12); System.out.println("Result = "+moveRight); System.out.println("Scale = " + moveRight.scale()); System.out.println("
Demonstrating scaleByPowerOfTen()..."); BigDecimal scaleRes = d.scaleByPowerOfTen(12); System.out.println("Result = "+scaleRes); System.out.println("Scale = " + scaleRes.scale()); } }
輸出
Value = 0.03676 Demonstrating moveRight()... Result = 36760000000 Scale = 0 Demonstrating scaleByPowerOfTen()... Result = 3.676E+10 Scale = -7
在上面的程式中,我們首先使用 movePointRight −
long base = 3676; int scale = 5; BigDecimal d = BigDecimal.valueOf(base, scale); System.out.println("Value = "+d); System.out.println("
Demonstrating moveRight()..."); BigDecimal moveRight = d.movePointRight(12); System.out.println("Result = "+moveRight); System.out.println("Scale = " + moveRight.scale());
然後我們實現了 scaleByPowerOfTen −
long base = 3676; int scale = 5; BigDecimal d = BigDecimal.valueOf(base, scale); System.out.println("Value = "+d); System.out.println("
Demonstrating scaleByPowerOfTen()..."); BigDecimal scaleRes = d.scaleByPowerOfTen(12); System.out.println("Result = "+scaleRes); System.out.println("Scale = " + scaleRes.scale());
廣告