英文:
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
。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论