Search code examples
javascripthtmlnumbersprojectcalculator

Why does my Vanilla JS Calculator's number change at the 17th digit?


It's a basic calculator made by the youtube channel Web Dev Simplified. He did a youtube tutorial on it, which I followed along and basically made the same thing.

Both his example calculator and mine has the same problem, where if I pressed on any of the number buttons (for example '1') 17 or more times, the numbers entered after the 16th digit displays as a different number for some reason (17th digit becomes '2' and not '1').

It does this with any number entered. I don't understand why.

I attached a codepen link so that you can see both his code and the code output.

You will find the display output in this part of the HTML code:

  <div class="output">
  <div data-previous-operand class="previous-operand"></div>
  <div data-current-operand class="current-operand"></div>
  </div>

Solution

  • it is because your number is over than integer add console.log() in the getDisplayNumber function and Compare the log and the display data

    in the log, it looks like 1.1111111111111111e+21 when out of the range

    What is JavaScript's highest integer value that a number can go to without losing precision?

    getDisplayNumber(number) {
    const stringNumber = number.toString()
    const integerDigits = parseFloat(stringNumber.split('.')[0])
    const decimalDigits = stringNumber.split('.')[1]
    console.log(integerDigits)
    let integerDisplay
    if (isNaN(integerDigits)) {
      integerDisplay = ''
    } else {
      integerDisplay = integerDigits.toLocaleString('en', { maximumFractionDigits: 0 })
    }
    if (decimalDigits != null) {
      return `${integerDisplay}.${decimalDigits}`
    } else {
      return integerDisplay
    }   }