从未缩放的长整数创建BigDecimal

huangapple go评论51阅读模式
英文:

Create BigDecimal from unscaled long

问题

我正在尝试将长整数1099转换为BigDecimal的10.99;这给我了11.00:long cost = 1099; MathContext CENTS = new MathContext(2,RoundingMode.HALF_EVEN); BigDecimal result = (new BigDecimal(cost,CENTS)).movePointLeft(2); 据我所知,这应该可以工作。我的愚蠢错误是什么?

英文:

I'm trying to convert long 1099 to BigDecimal 10.99;
This gives me 11.00:

long cost = 1099;
MathContext CENTS = new MathContext(2,RoundingMode.HALF_EVEN);
BigDecimal result = (new BigDecimal(cost,CENTS)).movePointLeft(2);

AFAIK this should work. What's my bonehead error?

答案1

得分: 2

错误在于精度和标度之间有一个区别。 MathContext 的构造函数接受一个精度,这是小数点两边的十进制数字的总数。 (例如,您最初的 BigDecimal 实际上是 11 * 10^2,就好像它是科学计数法。)

将其更改为 new MathContext(4, RoundingMode.HALF_EVEN)

英文:

The error is that there's a distinction between scale and precision. The constructor of MathContext accepts a precision, which is a total number of decimal digits on either side of the decimal point. (For example, the original BigDecimal you had was essentially 11 * 10^2, as if it were in scientific notation.)

Change it to new MathContext(4, RoundingMode.HALF_EVEN).

答案2

得分: 0

使用仅接受 long 参数的构造函数,不需要 MathContext

IdeOne.com 上查看此代码的实时运行

英文:
new BigDecimal( 1099L )
.movePointLeft(2)

Use constructor taking only a long, without the MathContext.

See this code run live at IdeOne.com.

答案3

得分: 0

Use the BigDecimal.valueOf(long unscaledVal, int scale) method:

long cost = 1099;
BigDecimal result = BigDecimal.valueOf(cost, 2);
System.out.println(result); // 10.99
英文:

Use the BigDecimal.valueOf(long unscaledVal, int scale) method:

long cost = 1099;
BigDecimal result = BigDecimal.valueOf(cost, 2);
System.out.println(result); // 10.99

huangapple
  • 本文由 发表于 2020年7月30日 05:56:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63163036.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定