0

I want to create a For-loop that add values to a list from 0.1 to 0.9. I did the following:

final List<double> speechRateValues = [];

for (int j = 0; j < 10; j++) {
      double value = 0.1 * j;
      speechRateValues.add(value);
    }

The problem is that my list is:

List

Is it possible to the 0.3000000... be just 0.3, and so on? I'm doing something wrong?

  • I read on another post a comment saying: "To prevent being bitten by artifacts of floating point arithmetic, you might want to use an integer loop variable and derive the floating point value you need inside your loop" so I did this way, but this still get "wrong" values – WilliamKose Feb 22 '23 at 16:58
  • If you are asking about this other way you did it, *show* what it is. – Scott Hunter Feb 22 '23 at 17:02
  • Sorry, the post already shows "the other way". – WilliamKose Feb 22 '23 at 17:04
  • 2
    This is the nature of floating point numbers – they're an approximation. The error in this case is less than one part in a million billion, which is extraordinarily close to zero, and for speech rates surely irrelevant. When you output the values you can use `toStringAsFixed` to format it in a way that disguises the very slight approximation. – motto Feb 22 '23 at 17:04

1 Answers1

0

I was thinking that this variation could cause trouble. But, as shown in this post: Dart, float for loop will cause strange result (thanks, Scott Hunter), this is how double number works, and in this case, this variation is irrelevant.

PS. To output the value, I can just use toStringAsFixed (to show 0.3, for example, properly) like motto said.