解析印地语数字时的NumberFormatException
我有一个Android应用程序,今天我有一个崩溃报告,其中包含:
当应用程序尝试解析用户提供的字符串编号时,会触发此exception。
很明显,问题是应用程序无法解析印地语数字! 那么,我该如何解决这个问题呢?
正则表达式
如果你想匹配任何unicode数字,使用正则表达式会更好。正则表达式将是\\p{N}+
,以下是如何使用它:
Matcher m=Pattern.compile("\\p{N}+").matcher(input); if(m.find()) { System.out.println(m.group()); }
语言环境
要回答您的问题,您应该使用文档中提到的NumberFormat 。 为NumberFormat
指定Locale
。
NumberFormat nf = NumberFormat.getInstance(new Locale("hi", "IN")); nf.parse(input);
您可以使用Character.getNumericValue(char) 。
这种方法的好处是它可以做你需要的。
但要有效工作,您应该在您的应用程序支持本地实现。
NumberFormat format = NumberFormat.getInstance(new Locale("hin","IND")); Number parse = format.parse("१"); System.out.println(parse);
打印1
。
试试这个。 这将删除非数字字符。
Pattern p = Pattern.compile("(\\d+)"); Matcher m = p.matcher(str); // str is input String while(m.find()) { System.out.println(m.group(1)); }
如果你正在处理double
(带小数位)。 你可以试试这个
String text = "123.0114cc"; String numOnly = text.replaceAll("\\p{Alpha}",""); double numVal = Double.valueOf(numOnly); System.out.println(numVal);
使用
BigDecimal bigDecimal = new BigDecimal(YOUR_VALUE);
在应用正则表达式之前,因为BigDecimal支持12个整数,12.35十进制和12 $货币,12%百分比及其本地化值。
您可以使用以下方法接收字符串并将其中的每个印度数字转换为阿拉伯语。
public static String convertAllIndianToArabic(String str) { for(int i=0; i