奇怪的双到字符串的转换 [英] Strange double-to-string conversion
问题描述
我用下面的code在我的活动之一来填充微调...
I am using the following code to populate a Spinner in one of my Activities...
for( double i = 0; i < 10 ; i+=0.1 ) {
rVoltsList.add( Double.toString( i ) );
}
Spinner rVoltsSpinner = (Spinner) findViewById( R.id.recloseVoltsSpinner );
ArrayAdapter<String> rVoltsAdapter = new ArrayAdapter<String>( this, android.R.layout.simple_spinner_item, rVoltsList );
rVoltsSpinner.setAdapter( rVoltsAdapter );
我是假设这会给我一个名单如下:0.0,0.1,0.2,0.3,0.4,依此类推。
然而,这是该列表看起来什么,当我运行我的程序,如:
I was assuming this would give me a list as follows : 0.0, 0.1, 0.2, 0.3, 0.4, and so on. However, this is what the list looks like when I run my program:
0.0
0.1
0.2
0.30000000000000000000000004
0.4
0.5
0.6
0.7
0.79999999999999999999
0.89999999999999999999
0.99999999999999999999
1.09999999999999999999
1.2
1.3
and this goes on until 9.99999999999999999998
什么想法?
推荐答案
使用这样的:
rVoltsList.add( String.format("%.1f", i) );
问题是, Double.toString(我)
将不是圆的。
但奇怪的值是由于一个事实,即0.1(基数为10)没有一个确切的再presentation为双击
在Java中,所以每次时间它添加到循环变量,要添加的东西比你想的是什么(请原谅我的双关语)有一点不同。
The strange values are due to the fact that 0.1 (base 10) does not have an exact representation as a double
in Java, so every time you add it to the loop variable, you are adding something a bit different than what you think (if you'll pardon the pun).
舍入的同一个问题建议您不要使用被双
作为循环变量。你是不太可能恰好准确地打你的循环限制。我会改写你的循环如下:
The same issue of rounding suggests that you should not be using a double
as a loop variable. You are very unlikely to exactly hit your loop limit exactly. I would rewrite your loop as follows:
for( int i = 0; i < 100 ; ++i ) {
rVoltsList.add( String.format("%.1f", i / 10.0) );
}
这篇关于奇怪的双到字符串的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!