Java小数点数字和百分号数字之间的转换

小数点数字和百分号(百分比)数字之间的转换在证券金融业很常见,需要经常进行两者之间相互转换。如代码:

        String s1 = "21.8%"; 
        String s2 = "-21.7%"; 
 
        NumberFormat numberFormat = NumberFormat.getPercentInstance(); 
        try { 
            Number n1 = numberFormat.parse(s1); 
            Number n2 = numberFormat.parse(s2); 
            Log.d("小数点字符串转百分数", n1.floatValue() + " , " + n2.floatValue()); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
 
        float f1 = 0.218f; 
        float f2 = -0.217f; 
        try { 
            numberFormat.setMaximumFractionDigits(3); //精确到3位。 
 
            String s3 = numberFormat.format(f1); 
            String s4 = numberFormat.format(f2); 
 
            Log.d("小数点数字转百分数字符串", s3 + " , " + s4); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        }

输出:

04-19 13:41:22.916 18485-18485/zhangphil.test D/小数点字符串转百分数: 0.218 , -0.217 
04-19 13:41:22.916 18485-18485/zhangphil.test D/小数点数字转百分数字符串: 21.8% , -21.7%


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!