简体   繁体   中英

How to convert a String into percentage value upto 2 decimal places

I have a string whose value will be like '1/3' or '1/2'. It can be even '2/3'. I need to convert it into its equivalent percentage value upto 2 decimal places and again convert it into String.

Is there any java API already present which does it automatically?

Please let me know if you know any optimum solution for this.

below code might resolve this:

import java.util.StringTokenizer;


public class percentage {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String x="2/3";
        System.out.println(convert(x));

    }
    public static String convert(String x){
        int num=0;
        StringTokenizer s= new StringTokenizer(x, "/");
        while(s.hasMoreElements()){
            num =Integer.parseInt(s.nextToken())/Integer.parseInt(s.nextToken());
        }
        return num+"";
    }
}

I have wrote a method of my own to resolve this. convert() method would return a String which gives the desirable output.

To convert a double to a percentage String you can use:

double number = ...;

NumberFormat numberFormat = NumberFormat.getPercentInstance();
numberFormat.setMaximumFractionDigits(2);
String formattedString = numberFormat.format(number);

您可以创建自己的方法,简单地用“/”分割字符串,然后将字符串(数组的)分子和分母解析为双精度。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM