1

I have a simple function, that should generate 1000 different elements:

var start = 0,
step = 0.0001

for (var i=0; i<1000; i++){
  console.log(start);
  start -= i*step;
  console.log(start);
}

The trouble is that I'm getting not precisely what I've expected:

enter image description here

How do I get price numbers in that case? Actually I need 0 -0.0001 -0.0002 -0.0003 ...

should I round those numbers all the time or there is simplier solution?

Prosto Trader
  • 3,471
  • 3
  • 31
  • 52

1 Answers1

0

Floating point numbers are not precise! However, you're not helping the situation, because you're compounding the imprecision. Instead of repeatedly subtracting from start, why don't you compute each value individually.

edit: incorrect code removed

The numbers aren't going to be perfect but at least this mitigates the problem of floating point precision, as each value doesn't depend on the last.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • Which gives a totally different result than what the OP is doing... `start -= i*step;` !== `out = -i * step;` – epascarello Mar 11 '14 at 13:08
  • it's not the case for me. in whole i have noumerous stock quotes on the page and when user selects one of them, I need to substract minimum step from that quote and get "next best" quote as if var Q = 500.25 var min_step = 0.01 and I need to get 500.24 – Prosto Trader Mar 11 '14 at 13:08
  • My code is completely incorrect, please ignore it. If the answers to the other question don't help you, you should edit this one. – Tom Fenech Mar 11 '14 at 13:17