比较Java中的BigDecimal movePointRight和scaleByPowerOfTen
java.math.BigDecimal.movePointRight(intn)返回一个与该小数点等效的BigDecimal(将小数点向右移n位)。如果n为非负数,则调用仅从小数位数中减去n。
java.math.BigDecimal.scaleByPowerOfTen(intn)返回一个BigDecimal,其数值等于(this*10n)。结果的小数位数为(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("\nDemonstrating moveRight()..."); BigDecimal moveRight = d.movePointRight(12); System.out.println("Result = "+moveRight); System.out.println("Scale = " + moveRight.scale()); System.out.println("\nDemonstrating 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("\nDemonstrating 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("\nDemonstrating scaleByPowerOfTen()..."); BigDecimal scaleRes = d.scaleByPowerOfTen(12); System.out.println("Result = "+scaleRes); System.out.println("Scale = " + scaleRes.scale());