What is the difference between BigDecimal movePointRight and scaleByPowerOfTen?

蓝咒 提交于 2019-12-05 12:37:27

问题


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?


回答1:


  • 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



回答2:


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



来源:https://stackoverflow.com/questions/25454734/what-is-the-difference-between-bigdecimal-movepointright-and-scalebypoweroften

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!