Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between BigDecimal movePointRight and scaleByPowerOfTen?

With the following code:

BigDecimal x = new BigDecimal("34.5678");
BigDecimal a = x.movePointRight(3);
BigDecimal b = x.scaleByPowerOfTen(3);
BigDecimal c = x.movePointRight(-3);
BigDecimal d = x.scaleByPowerOfTen(-3);

a and b are both 34567.8 and c and d are both 0.0345678. a.scale() and b.scale are both 1 and c.scale() and d.scale() are both 7.

In what circumstances do these two methods produce different results?

like image 789
Steve Waring Avatar asked Aug 22 '14 19:08

Steve Waring


People also ask

What is BigDecimal scale?

A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale.

Can BigDecimal have negative values?

The value of the BigDecimal is (BigInteger/10**scale). A negative scale will result in a NumberFormatException.

Does BigDecimal support decimal places?

In java, BigDecimal consists of a random precision integer scale and a 32-bit integer scale. If positive or zero, the scale is the number of digits to the right of the decimal point.


2 Answers

  • movePointRight will prevent a negative scale from occurring if it results in one.
  • scaleByPowerOfTen will not prevent this.

Example code:

import java.math.BigDecimal;

public class BigDecimalScale {
  public static void main(String... args) {
    long base = 12345;
    int scale = 4;

    BigDecimal number = BigDecimal.valueOf(base, scale);
    System.out.println(number);
    BigDecimal pointRight = number.movePointRight(5);
    System.out.println(pointRight + "; my scale is " + pointRight.scale());
    BigDecimal scaleBy = number.scaleByPowerOfTen(5);
    System.out.println(scaleBy + "; my scale is " + scaleBy.scale());
  }
}

Result:

1.2345
123450; my scale is 0
1.2345E+5; my scale is -1
like image 175
durron597 Avatar answered Nov 15 '22 14:11

durron597


I've found the answer. If x is declared as

BigDecimal x = new BigDecimal("34.5678", new MathContext(4));

Then a has a scale of 0, but b has a scale of -1. a.toString() gives 34570, b.toString() gives 3.457E+4

like image 35
Steve Waring Avatar answered Nov 15 '22 14:11

Steve Waring