简体   繁体   中英

float doesn't return in SharedPreferences

Why float doesn't return the wanted value in another activity. All the other ints, and Strings does, but float doesn't.

Sender activity:

 SharedPreferences prefs = this.getSharedPreferences(
                        "details", Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = prefs.edit();
                edit.putInt("weight", weight);
                edit.putInt("height", height);
                edit.putInt("age", ag);
                edit.commit();

Log.d("BMI Height" , String.valueOf(height));
Log.d("BMI Weight" , String.valueOf(weight));

BMI Height and weight in the console are the correct

Receiver activity:

 SharedPreferences prefs = getSharedPreferences(
            "details", Context.MODE_PRIVATE);

    int age=prefs.getInt("age", Integer.parseInt("16"));
    int weight=prefs.getInt("weight", Integer.parseInt("50"));
    int height=prefs.getInt("height", Integer.parseInt("165"));

Log.d("BMI Height" , String.valueOf(height));
Log.d("BMI Weight" , String.valueOf(weight));

    float formula = weight / (height * height) * 10000;

    Log.d("BMI Formula", String.valueOf(formula));

BMI Height and weight in the console are the still correct, but formula returns 0.0 in the console.

Because you're doing math on integers and storing the result in a float. The math is still done on integers. So you'll divide weight (50) by height*height (around 10K). THat's less than 1, but the result of dividing two integers is always an integer. So it rounds to 0.

To fix that, make weight and height floats.

try like this

edit.putFloat("key", (float) 10.10);

and try to get the value

prefs.getFloat("key", (float) 10.0);

since weight and height are integers so probably the result should be zero. For example

int a = 10
int b = 5

float c = a/(b*b);

it will return 0 because calculation in int results 0 and then it will typecast into float 0.0 you can typecast weight and height to float like

float c = (float)a/((float)b*(float)b);

then it will return you 0.400

The problem here is you are dividing ints, the result is then automatically cast to float, So if the result isn't great enough you get 0 (and either way you'd get an int).

You have to cast the first int in the division to float to get the desired result.

float formula = (float) weight / (height * height) * 10000;

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