2012-01-03 79 views
0

我有一个方法返回类型为ArrayList<String>,它也读取相同类型的参数。现在我该如何type cast或修改我的BigDecimal来读取该值?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; 
} 

或者我需要做的

+0

你是不是想一个ArrayList的''转换为一个ArrayList的''? – Gabe 2012-01-03 07:26:55

+0

@Gabe一个方法会调用并发送值列表,现在说''1234.5678'和'4567.1234'这两个值到'currUtil'这个方法现在我需要定义我的方法'currUtil',这样它就读取值并将其放置在BigDecimal中一个接一个地处理它。如何定义我的方法? – 2012-01-03 07:35:44

回答

1

您不能键入一个String转换为BigDecimal反之亦然

如果阵列中的字符串是指当串联来表示一个号码,然后这样做:

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

在另一方面,如果每个字符串代表一个不同的号码:

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

我不认为你正确地引用它。您不能将整个ArrayList作为字符串类型的AL转换为大十进制。

首先,从新的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))); 
} 

我认为,应该给你你需要什么返回时。

+0

我其实很困惑这个问题。这个罗嗦很难准确地指出你在问什么。如果你正在尝试创建一个ArrayList ,那么使用我的代码,但改变for循环之间的内容,因为这不会给你其他可能性。 – Andy 2012-01-03 07:50:13

0

我的理解是您要将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)); 
}