2

I am getting the json data from an API as String but I want to store it in DB and use it as integer. For example I am getting A=15K or 15M but I want 15000.

Here is my class

public class JsonRestApi {
    public JsonRestApi() {
        try {
            String Response = "{\"Youtube Data\":{\"Views\":\"15K\"}}";

            JSONParser parser = new JSONParser();
            try {
                Object obj = parser.parse(Response);

                JSONObject jsonObject = (JSONObject) obj;
                JSONObject jsonObject3  = (JSONObject)jsonObject.get("Youtube Data");

                String yviews = (String)jsonObject3.get("Views");
                System.out.println(yviews);
            }
        }
     }
 } 

Output- 15K

But I want output as 15000. However I do not want to change my Json data. How should I accomplish this?

6
  • Why 15000? 10K is 10000?! Commented Sep 29, 2016 at 8:46
  • 1
    see codereview.stackexchange.com/questions/77697/… Commented Sep 29, 2016 at 8:47
  • Try to get last character and multiply value. Commented Sep 29, 2016 at 8:47
  • s = s.replaceFirst("(?i)\\s*K$", "000").replaceFirst("(?i)\\s*M$", "000000").replaceFirst("(?i)\\s*G$", "000000000") Commented Sep 29, 2016 at 8:54
  • 1
    @Joop Suppose if I have views = 15.4K value then according to your code it would print 15.4000 but what i want is 15400 Commented Sep 29, 2016 at 9:03

1 Answer 1

5

Replace K, M etc. with the appropriate number of zeroes.

String yviews = (String)jsonObject3.get("Views");
yviews = yviews.replace( "K", "000").replace( "M", "000000");
System.out.println(yviews);

Edit: If your number of views can have floating point numbers, you can use the following code:

String[][] conversionMatrix = {{"K", "1000"}, {"M", "1000000"}, {"B", "1000000000"}};

for( int i = 0; i < conversionMatrix.length; i++)
{
    if( yviews.endsWith( conversionMatrix[i][0]))
    {
        BigDecimal temp = new BigDecimal( yviews.substring( 0, 
                                            yviews.indexOf( conversionMatrix[i][0])));
        temp = temp.multiply( new BigDecimal( conversionMatrix[i][1]));
        yviews = temp.toBigInteger().toString();
        break;
    }
}

System.out.println( yviews);
Sign up to request clarification or add additional context in comments.

2 Comments

Suppose if I have views = 15.4K value then according to your code it would print 15.4000 but what i want is 15400
If your views can have floating point numbers, you need a different approach, see the edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.