如何将带有句点和逗号的String转换为int,如
String a "9.000,00"
int b = Integer.parseInt(a);
当我运行此代码时,收到一条错误消息:Exception in thread "main" java.lang.NumberFormatException: For input string: "9.000,00"
答案 0 :(得分:4)
如果您想获得结果900000
,那么只需移除所有,
和.
,然后使用Integer.parseInt
或Long.parseLong
解析它如果数字可能很大,甚至可以更好地使用BigInteger
。
String a = "9.000,00";
BigInteger bn = new BigInteger(a.replaceAll("[.,]", ""));
System.out.println(bn);
输出:900000
但是,如果您要将9.000,00
解析为9000
(其中,00
部分是小数部分),那么您可以NumberFormat
使用Locale.GERMANY
使用表单类似于您的输入:123.456,78
String a = "9.000,00";
NumberFormat format = NumberFormat.getInstance(Locale.GERMANY);
Number number = format.parse(a);
double value = number.doubleValue();
//or if you want int
int intValue = number.intValue();
System.out.println(value);
System.out.println(intValue);
输出:
9000.0
9000
答案 1 :(得分:3)
final String a = "9.000,00";
final NumberFormat format = NumberFormat.getInstance(Locale.GERMAN); // Use German locale for number formats
final Number number = format.parse(a); // Parse the number
int i = number.intValue(); // Get the integer value
答案 2 :(得分:2)
为此,您需要使用java.text.NumberFormat
和NumberFormat.getInstance(Locale.FRANCE)
(或其他兼容的Locale
)
import java.text.NumberFormat;
import java.util.Locale;
class Test {
public static void main(String[] args) throws Exception {
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
String a = "9.000,00";
a = a.replaceAll("\\.", "");
Number number = format.parse(a);
double d = number.doubleValue();
int c = (int) Math.floor(d);
System.out.println(c);
}
}
根据需要打印9000
(现在是int
)!
如果我打印每个中间步骤:
import java.text.NumberFormat;
import java.util.*;
class test {
public static void main(String[] args) throws Exception {
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
String a = "9.000,00";
a = a.replaceAll("\\.", "");
System.out.println(a); // prints 9000,00
Number number = format.parse(a);
System.out.println(number); // prints 9000
double d = number.doubleValue();
System.out.println(d); // prints 9000.0
int c = (int) Math.floor(d);
System.out.println(c); // prints 9000
}
}
所以,如果你想要9000,00
想要在你的评论中说出来,那么你只需要
a = a.replaceAll("\\.", "");
System.out.println(a);
为您提供9000,00
我希望有所帮助。
答案 3 :(得分:1)
试试这个 -
String a = "9.000,00";
a = a.replace(",","");
a = a.replace(".","");
int b = Integer.parseInt(a);
答案 4 :(得分:1)
我认为DecimalFormat.parse是Java 7 API的方法:
String a = "9.000,00";
DecimalFormat foo = new DecimalFormat();
Number bar = foo.parse(a, new ParsePosition(0));
在那之后,你会对你刚刚得到的Number感到满意。
如果您希望答案为900000(对我来说没有意义,但我正在回复您的问题)并将其放入 int 跟着:
int b = Integer.parseInt(a.replaceAll(",","").replaceAll("\\.",""));
已如评论中所述。