gpt4 book ai didi

java - BigDecimal movePointRight 和 scaleByPowerOfTen 有什么区别?

转载 作者:搜寻专家 更新时间:2023-10-30 19:44:48 25 4
gpt4 key购买 nike

使用以下代码:

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 和 b 都是 34567.8,c 和 d 都是 0.0345678。a.scale()b.scale都是1,c.scale()d.scale() 都是 7.

这两种方法在什么情况下会产生不同的结果?

最佳答案

  • movePointRight 将防止出现负比例(如果它导致负比例)。
  • scaleByPowerOfTen 不会阻止这种情况。

示例代码:

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

结果:

1.2345
123450; my scale is 0
1.2345E+5; my scale is -1

关于java - BigDecimal movePointRight 和 scaleByPowerOfTen 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25454734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com