我需要将价格转换为整数,例如:
我该怎么做?
答案 0 :(得分:1)
使用NumberFormat.getCurrencyInstance()
:
NumberFormat nf = NumberFormat.getCurrencyInstance(); // Use Locale?
int[] ints = new int[strings.length];
for(int i = 0 ; i < strings.length ; ++i) {
ints[i] = nf.parse(strings[i]).intValue();
}
答案 1 :(得分:0)
public static int convertDoubleToInt(double d){
//rounds off to the nearest 100
long l = Math.round(d);
int i = (int) l;
return i;
}
public static double convertCommaDoubleToInt(String s) throws ParseException{
NumberFormat nf = NumberFormat.getInstance(Locale.US);
Number number = nf.parse(s);
return number.doubleValue();
}
public static void main(String[] args) throws ParseException {
String[] moneys = {"12,000", "245.76"};
for(String n: moneys){
Double d = convertCommaDoubleToInt(n);//first remove the comma, if there
System.out.println(convertDoubleToInt(d)); //then convert double into int
}
}
答案 2 :(得分:0)
比其他解决方案短得多:
public static int parseStringToInt(String s){
s = s.replaceAll(",", ""); //remove commas
return (int)Math.round(Double.parseDouble(s)); //return rounded double cast to int
}
像这样使用它:
public static void main(String[] args) {
String[] m = {"12,000", "245.67"};
for (String s : m){
System.out.println(parseStringToInt(s));
}
}