Compare BigDecimal movePointRight and scaleByPowerOfTen in Java

Java 8Object Oriented ProgrammingProgramming

The java.math.BigDecimal.movePointRight(int n) returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the right. If n is non-negative, the call merely subtracts n from the scale.

The java.math.BigDecimal.scaleByPowerOfTen(int n) returns a BigDecimal whose numerical value is equal to (this * 10n). The scale of the result is (this.scale() - n).

The following is an example displaying the usage of both −

Example

 Live Demo

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());
   }
}

Output

Value = 0.03676
Demonstrating moveRight()...
Result = 36760000000
Scale = 0
Demonstrating scaleByPowerOfTen()...
Result = 3.676E+10
Scale = -7

In the above program, first we worked on 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());

Then we implemented 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());
raja
Published on 25-Apr-2019 09:10:59
Advertisements