Java 将 Long 转换为 BigDecimal
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/921621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
cast Long to BigDecimal
提问by Suresh Chaganti
How can I cast Long
to BigDecimal
?
我怎样才能投射Long
到BigDecimal
?
采纳答案by Silfverstrom
You'll have to create a new BigDecimal
.
您必须创建一个新的BigDecimal
.
BigDecimal d = new BigDecimal(long);
回答by jjnguy
You can't cast it. You can create a new BigDecimal
though. You can get a long
from a Long
using Long.getLongValue()
if you have the non-primitave Long.
你不能投。你可以创建一个新的BigDecimal
。如果你有非原始的 Long,你可以long
从Long
using 中得到 a Long.getLongValue()
。
BigDecimal bigD = new BigDecimal(longVal);
回答by Fredou
回答by Mike Pone
You need to create a new BigDecimal object
您需要创建一个新的 BigDecimal 对象
Long test = new Long (10);
BigDecimal bigD = new BigDecimal(test.longValue());
回答by Gareth Davis
For completeness you can use:
为了完整起见,您可以使用:
// valueOf will return cached instances for values zero through to ten
BigDecimal d = BigDecimal.valueOf(yourLong);
0 - 10 is as of the java 6 implementation, not sure about previous JDK's
0 - 10 从 java 6 实现开始,不确定以前的 JDK
回答by Fico
You should not use BigDecimal d = new BigDecimal(long); !!
你不应该使用 BigDecimal d = new BigDecimal(long); !!
The implementation in BigDecimal for longs is not precise. For financial applications this is critical!
BigDecimal 中 longs 的实现并不精确。对于金融应用,这是至关重要的!
But the implementation for the String argument is better! So use something like:
但是 String 参数的实现更好!所以使用类似的东西:
new BigDecimal(yourLong.toString());
There was a talk on http://www.parleys.com/about this.
在http://www.parleys.com/上有一个关于这个的讨论。