# 从未缩放的长整数创建BigDecimal

go评论51阅读模式

Create BigDecimal from unscaled long

# 问题

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

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

``````new BigDecimal( 1099L )
.movePointLeft(2)
``````

Use constructor taking only a `long`, without the `MathContext`.

See this code run live at IdeOne.com.

# 答案3

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

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

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

go 49

go 48

go 56

go 38