简体   繁体   English

从Float转换为整数

[英]Convert from Float to integer

I built a simple Android "accelerometer" Sensor Application. 我构建了一个简单的Android“加速度计”传感器应用程序。

This is The Java Code link . 这是Java代码链接

The output is like this: 输出是这样的:

X:8.87654322 Y:0.564321 Z:4.0195783 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 我想将浮点数转换为整数或只有2个数字

(I'm a beginner In Java.) (我是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]) 我想您想将加速度计的浮点数组值转换为int,以下是具有两个浮点值的浮点数组,我只是使用Math.round(arrayname [indexnumber])四舍五入另一个索引的float元素的值

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 这将舍入前6574.748的浮点值将四舍五入为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 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: ) 要获得两位小数,请使用( 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. 对于整数,帖子中还有其他答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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