1

I'm trying to get an array of numbers from some min to max by a decimal interval, in this case, 0.02, for example: 1.00, 1.02, 1.04, 1.06

The code below starts to break at the number 1.14:

function getOptions(min, max, interval) {
  var options = [];

  for (var i = min; i <= max; i += interval) {
    options.push(i);
  }

  return options;
}

var options = getOptions(1.0, 1.4, 0.02);

At this point, options is like:

[
    1, 
    1.02, 
    ...
    1.12, 
    1.1400000000000001, 
    1.1600000000000001
    ...
]

What causes this and how can I fix it?

2
  • try - options.push(parseFloat(i.toFixed(2)));, where toFixed(n) converts the input to string keeping n number of decimals. Commented May 21, 2015 at 16:57
  • @BatScream, that's my answer. In fact, I was using options.push(i.toFixed(2) prior to posting the question, but my loop wasn't working because it wasn't inclusive on i <= max -- using i.toFixed(2) <= max is what I needed. Commented May 21, 2015 at 17:00

1 Answer 1

3

As per What Every Programmer Should Know About Floating-Point Arithmetic:

internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.

When the code is compiled or interpreted, your “0.1” is already rounded to the nearest number in that format, which results in a small rounding error even before the calculation happens.

For Javascript specifically:

JavaScript numbers are really just floating points as specified by IEEE-754. Due to inadequecies when representing numbers in base-2, as well as a finite machine, we are left with a format that is filled with rounding errors. This article explains those rounding errors and why errors occur. Always use a good library for numbers instead of building your own

I have had some success with this BigDecimal port and the smaller, faster big.js.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.