简体   繁体   中英

Convert from Float to integer

I built a simple Android "accelerometer" Sensor Application.

This is The Java Code link .

The output is like this:

X:8.87654322 Y:0.564321 Z:4.0195783

And sometimes it goes longer ...

I want to convert the float to an integer or just have 2 numbers

(I'm a beginner In Java.)
Thanks

double y = 9.37923929732232;
int a = (int)y;
double d = 4.232
int answer = (int) Math.round(d);

i think you want to convert float array values of accelerometer to int below is the float array with two float values i am just rounding off the value of float element of oth index using Math.round(arrayname[indexnumber])

float[] fArray = new float[] {(float) 6574.748, (float) 789.999};

    int f1 = Math.round(fArray[0]);
    System.out.println(f1);

this will round off the float value for ex 6574.748 will be rounded to 6575

To convert float sensor data to integer you have to mutiply them, and then round.

eg you want 1 digit after comma. 0.56432 -> 6

double y = 0.564321;
int yi = (int) Math.Round(y * 10); // for taking 2 digits after comma use 100

Then you have handy acceleration sensor data.

For getting two decimal places use ( java.text.DecimalFormat: )

You can try this

 double roundTwoDecimals(double d) { 
    DecimalFormat twoDForm = new DecimalFormat("#.##"); 
    return Double.valueOf(twoDForm.format(d));
 }  

For integer there are other answers in the post.

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