【问题标题】:Type casting for BigDecimalBigDecimal 的类型转换
【发布时间】:2012-02-01 07:18:00
【问题描述】:

我有一个方法返回类型为ArrayList<String>,它也在读取相同类型的参数。现在我如何type cast 或修改我的 BigDecimal 以读取该值?

public static ArrayList<String> currencyUtilArray(ArrayList<String> amountStr ) {
BigDecimal amount = new BigDecimal(ArrayList<String> amountStr);
//How do I define that the amountStr is ArrayList<String> and need to place in BigDecimal amount one after another till the end of the List 
    return amountStr;
}

或者我需要这样做

【问题讨论】:

  • 您是否尝试将ArrayList&lt;String&gt; 转换为ArrayList&lt;BigDecimal&gt;
  • @Gabe 一种方法会调用并发送值列表,现在说两个值,如1234.56784567.1234 给这个方法currUtil 现在我需要定义我的方法currUtil 这样一种读取值并将其逐个放入 BigDecimal 以对其进行处理的方式。如何定义我的方法?

标签: java string casting arraylist bigdecimal


【解决方案1】:

我认为您没有正确引用它。您不能将整个 ArrayList 作为字符串类型的 AL 转换为 Big Decimal。

首先,从 new BigDecimal(--); 中更改 ArrayList amountStr;并从 ArrayList 中引用单个字符串。

这意味着你必须遍历整个事情,将其添加到数量中:

BigDecimal amount = new BigDecimal(amountStr.get(0));
For(int i = 1; i < amountStr.size(); i++){
amount = amount.add(new BigDecimal(amountStr.get(i)));
}

我相信当它被退回时应该会给你你需要的东西。

【讨论】:

  • 我实际上对这个问题很困惑。冗长的文字使您很难准确指出您要问的内容。如果您尝试制作 ArrayList,请使用我的代码,但更改 for 循环之间的内容,因为这不会给您带来其他可能性。
【解决方案2】:

您不能将String 类型转换为BigDecimal反之亦然

如果数组中的字符串在连接时表示一个数字,则执行以下操作:

 StringBuilder sb = new StringBuilder();
 for (String s : amountStr) {
     sb.append(s);
 }
 BigDecimal amount = new BigDecimal(sb.toString());

另一方面,如果每个 String 代表一个不同的数字:

for (String s : amountStr) {
    BigDecimal amount = new BigDecimal(s);
    // ... and do something with it ...
}

【讨论】:

    【解决方案3】:

    我的理解是您想将list elements 转换为BigDecimal Array。如果是这样,您可以执行以下操作:

    BigDecimal[] amount = new BigDecimal[amountStr.size()];
    for (int i=0;i<amountStr.size();i++) {
         amount[i] = new BigDecimal(amountStr.get(i));
     }
    

    【讨论】:

      猜你喜欢
      • 2014-04-04
      • 2021-12-16
      • 2012-05-30
      • 2011-05-01
      • 1970-01-01
      • 2012-09-05
      • 2019-10-11
      • 1970-01-01
      • 2013-08-26
      相关资源
      最近更新 更多