需要从NumberFormatted double获取原始双精度数据

时间:2012-07-21 13:42:05

标签: java number-formatting

我需要double值的百分比形式,所以我使用了NumberFormat

    double d = 0.13;   
    NumberFormat nf = NumberFormat.getPercentInstance();      
    String kpr = nf.format(kpr);  

我通过setter将此属性保存到对象Person。当我通过getter方法返回它时,它返回String(当然)  有没有办法将这个String去格式化为双精度值为0.13,以便我可以对其执行算术运算?

2 个答案:

答案 0 :(得分:0)

double d=(Double.parase(kpr.substring(kpr.length-1)))/100;

答案 1 :(得分:0)

public static void main(String s[]) {
    getDoubleFromStringWithPercent("12345%");
}

private static Double getDoubleFromStringWithPercent(String string) {
    Locale locale = Locale.CANADA;
    Double num = null;
    try {
        Number number = NumberFormat.getPercentInstance(locale).parse(string);
        if (number instanceof Long) {
            num = ((Long) number).doubleValue();
        } else {
            num = (Double) number;

        }
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
    return num;
}

Locale需要查找十进制分隔符(“。”或“,”);

替代版本:

String string ="2165%";

double d = Double.parseDouble(string.substring(0, string.length()-1));
if (d != 0) {
   d = d / 100;
}