George Lungu George Lungu - 5 months ago 10
Android Question

How to remove decimals from a float result?

in my app i calculate the CPU usage and i get the result in % but sometimes the result is too big 20.234234234234
My question is, how can i completely remove the result numbers after the "."?
And can i do this without changing float to integer?

Here is my code:


private float readCpuUsage() {
try {
RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
String load = reader.readLine();

String[] toks = load.split(" ");

long idle1 = Long.parseLong(toks[5]);
long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3])
+ Long.parseLong(toks[4]) + Long.parseLong(toks[6])
+ Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

try {
Thread.sleep(360);
} catch (Exception e) {
}

reader.seek(0);
load = reader.readLine();
reader.close();

toks = load.split(" ");

long idle2 = Long.parseLong(toks[5]);
long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3])
+ Long.parseLong(toks[4]) + Long.parseLong(toks[6])
+ Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

return (float) (cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));

} catch (IOException ex) {
ex.printStackTrace();
}

return 0;
}


To print the result i just throw:

textview.setText((readCpuUsage() * 100) + "%");


where readCpuUsage() is the result and to transform it to % i multiply it with 100

This is how i did it:

float xxz=readCpuUsage()*100;
textview.setText(String.format("%.0f",xxz) + "%");

Answer

Try This it may be help to you

String.format("%.0f",floatvalue);

or

Float.parseFloat(String.format("%.0f",floatvalue))