Compare BigDecimal movePointRight and scaleByPowerOfTen in Java



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());
Updated on: 2019-07-30T22:30:25+05:30

273 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements