Expand my Community achievements bar.

Decimal place issue when using for loop to populate dropdown box

Avatar

Level 1

This for loop on a dropdown change event:

for (var i = 0; i <= 1; i+=0.1) {

dropdown.addItem(i

+'');

returns the following output:

0

0.1

0.2

0.30000000000004

0.4

0.5

0.6

0.79999999999999

0.89999999999999

0.99999999999999

Does anybody know why and can anybody suggest a solution?

5 Replies

Avatar

Level 7

JavaScript (as great as it is)  is notorious for this sort of thing and as I read from a book recently: "You wouldn't want to land a space shuttle by having JavaScript do the calculations". Have you tried FormCalc?

Avatar

Level 1

Thanks for the advice.

I tried to insert a script object but FormCalc is disabled. Can I not create a function using FormCalc?

Avatar

Level 7

Just a thought...

.

You may have this problem because dropdown values are treated as strings--you may have to do a string manipulation in order to get the result you want. That is, use the substr() function.

Avatar

Level 7

You have to build a string for the addItem, This works:

for (var i = 0; i < 10; i++) {

     DropDownList1.addItem("1." + i);

}

Cheers,

Stephen

Avatar

Level 10

Hi, You can use the toFixed() method to format your numbers.

for (var i = 0; i <= 1; i+=0.1)
{
this.addItem(i.toFixed(1));
}

This also has the advantage of returning a string value so can be used in addItem directly.

Bruce