Android怎么把字符串转换成Integer/Float/Double 中的一种

Android怎么把字符串转换成Integer/Float/Double 中的一种

问题描述:

我想把字符串转换为Integer/Float/Double 中的一种,但是结果变成了NumberFormatException.。我的字符串是:37,78584,怎么样把他们转变为我想要的类型呢?
先谢谢帮我解答。

设置正确的locale

String s= "37,78584";
Number number= NumberFormat.getNumberInstance(Locale.FRENCH).parse(s);
double d= number.doubleValue();
System.out.println(d);

输出:

37.78584

将字符串转化为整型;

int i = Integer.parseIn(String str);

int i = Integer.valueOf().intValue();

注:Integer.parseIn 和 Integer.valueOf 不同,前者生成的是整型,而后者是一个对象,所以要通过intValue()来获得对象的值;

用""代替逗号(",")

  String s ="37,78584";
  int ival = Integer.parseInt(s.replace("," ,""));
  double dval=Double.parseDouble(s.replace("," ,""));
  float fval =Float.parseFloat(s.replace("," ,""));

使用""代替字符串里的

String str= "37,78584";str= str.replaceAll("\\,","");

Integer.parseInt("123");

Double.parseDouble("123");

Foloat.parseFloat();

Integer.parseInt("321")