简体   繁体   中英

Round number to only first decimal place

I would like to know the available phone memory, so I wrote this code.

File path2 = Environment.getDataDirectory();
StatFs stat2 = new StatFs(path.getPath());
long blockSize2 = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
double result = availableBlocks * blockSize;

free = (Preference)this.findPreference("free_mem");
free.setSummary(Double.toString(result)+" GB");

The problem is that I get a outpout as 5.654707363. I tried to take only the first decimal place using

free = Math.round(size * 10) / 10d;

But doesn't work. Any ideas?

If I understood your question right you need NumberFormat here:

NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(1);
nf.format(5.654707363);

produces 5,7

If you need the value for display purpose, use NumberFormat (see answer by Adam Arnold).

For numeric rounding (producing the rounded number), use BigDecimal :

double num = 3.141592653589793d;
double rounded = BigDecimal.valueOf(num).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();

Have you tried using free = Math.round(free * 10) / 10d; instead of free = Math.round(size * 10) / 10d; ? I don't see size as a defined variable.

A simple test of

double free = 5.654707363;
free = Math.round(free * 10) / 10d;
System.out.println(free);

outputs 5.7.

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