Calculations with String in Java

Asked

Viewed 170 times

2

I need to average some numbers I receive via JSON in the format of Strings, this calculation must return a value so that I can set it within a TextView on Android, but I’m not able to format this answer so it only comes with a decimal (example: the calculation returns 46.7) it’s returning a much higher value:

private Float calculateAverage(Powerstats powerstats) {
    float sum;

    sum = Float.parseFloat("70" + "26" + "83"
                + "55" + "81" + "69");

    return sum / 6;
}

the return of this function should be a number formatted with only 1 decimal place.

  • This sum of strings there is not doing what you think it is. You know which sign of + does not add strings, and yes CONCATENATE? This is what happens: https://ideone.com/wr1I4D

1 answer

9


In the way you put it doesn’t make sense to do this, if you already have the numbers use them directly, in fact you don’t even need to do math. But considering they’re actually variables you have to apply the parseFloat() in each of the variables, and with the individual number converted make the sum. There are still a number of things wrong that can happen there (for example the person typing something that is not a number), but that is another matter. It would be something like this for two variables:

return (Float.parseFloat(a) + Float.parseFloat(b)) / 2;

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • That’s right, I put the values there fixed just to illustrate, each value comes from a model class, in case I was doing Float.parseFloat(a + b) and so ended up concatenating the Strings and not summing them

Browser other questions tagged

You are not signed in. Login or sign up in order to post.