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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:06:54  来源:igfitidea点击:

cast Long to BigDecimal

javabigdecimal

提问by Suresh Chaganti

How can I cast Longto BigDecimal?

我怎样才能投射LongBigDecimal

采纳答案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 BigDecimalthough. You can get a longfrom a Longusing Long.getLongValue()if you have the non-primitave Long.

你不能投。你可以创建一个新的BigDecimal。如果你有非原始的 Long,你可以longLongusing 中得到 a Long.getLongValue()

BigDecimal bigD = new BigDecimal(longVal);

回答by Fredou

you have to create a new bigDecimal

你必须创建一个新的 bigDecimal

how to do it

怎么做

回答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/上有一个关于这个的讨论。