項目中有時會遇到對金額格式的數值如“1,234.34567”進行計算,直接使用Double.parseDouble(“1,234.34567”)會拋出NumberFormatException異常, 那么,有沒好的方法解析金額格式的數值?
jdk中提供了NumberFormat支持,它的format方法可以將數值轉成金額格式字符串,parse方法能解析金額格式的字符串,如下:
NumberFormat format = NumberFormat.getInstance(); String result = format.format(1234.34567); System.out.println(result);
double doubleValue; try { doubleValue = format.parse("1,234.34567").doubleValue(); System.out.println(doubleValue); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); }
輸出結果如下:
1,234.346 1234.34567