比对 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());

更新于: 2019 年 7 月 30 日

242 次浏览

开启您的 事业

完成课程后获得认证

开始
广告