根据传递字符串得到double值或者int型
package com.shopping.test;public class test { /** * 解析str,获得其中的整数 * @param str 待解析的str */ private static int getIntValue(String str) { int r = 0; if (str != null && str.length() != 0) { StringBuffer bf = new StringBuffer(); char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (c >= '0' && c <= '9') { bf.append(c); } else if (c == ',') { continue; } else { if (bf.length() != 0) { break; } } } try { r = Integer.parseInt(bf.toString()); } catch (Exception e) { } } return r; } /** * 解析字符串获得双精度型数值, * @param str * @return */ private static double getDoubleValue(String str) { double d = 0; if (str != null && str.length() != 0) { StringBuffer bf = new StringBuffer(); char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (c >= '0' && c <= '9') { bf.append(c); } else if (c == '.') { if (bf.length() == 0) { continue; } else if (bf.indexOf(".") != -1) { break; } else { bf.append(c); } } else { if (bf.length() != 0) { break; } } } try { d = Double.parseDouble(bf.toString()); } catch (Exception e) { } } return d; } public static void main(String[] args) { //1.5(参考代表值) String str1="1.5(参考代表值)"; // String str1="0.730000019073486"; double str1D = getDoubleValue(str1); System.out.println(str1+"->"+str1D); int i = getIntValue(str1); System.out.println(str1+"->"+i); }}
注意:这个方法只能获取一个值。