0

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

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

我通过 setter 将此属性保存到对象 Person 中。当我通过 getter 方法取回它时,它返回字符串(当然)。
有没有办法将此字符串取消格式以将值加倍为 0.13,以便我可以对其执行算术运算?

4

2 回答 2

0
double d=(Double.parase(kpr.substring(kpr.length-1)))/100;
于 2012-07-21T13:49:57.627 回答
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;
}

语言环境需要查找小数分隔符(“.”或“,”);

替代版本:

String string ="2165%";

double d = Double.parseDouble(string.substring(0, string.length()-1));
if (d != 0) {
   d = d / 100;
}
于 2012-07-21T13:50:01.073 回答