Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

android - Strange double-to-string conversion

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 );

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

any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use this:

rVoltsList.add( String.format("%.1f", i) );

The problem is that Double.toString(i) will not round.

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) );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...