简体   繁体   English

将数字舍入到仅小数点后一位

[英]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. 问题是我的支出为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

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

produces 5,7 产生5,7

If you need the value for display purpose, use NumberFormat (see answer by Adam Arnold). 如果需要用于显示的值,请使用NumberFormat (请参见Adam Arnold的回答)。

For numeric rounding (producing the rounded number), use BigDecimal : 对于数字舍入(产生舍入的数字),请使用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; 您是否尝试过使用free = Math.round(free * 10) / 10d; instead of free = Math.round(size * 10) / 10d; 而不是free = Math.round(size * 10) / 10d; ? I don't see size as a defined variable. 我不认为size是定义的变量。

A simple test of 一个简单的测试

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

outputs 5.7. 输出5.7。

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

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