I seem to be having an issue with the decimal point on my calculator - I only want to see one dot

Only need one dot for the calculator to function properly. The current situation with multiple dots is causing confusion. I intend to address other aspects of the code later, but I'm currently struggling with this issue.

 function dec(d) {

      let display = document.getElementById('display');
      let displayArray = display.innerHTML.split("");
      displayArray += d.innerHTML;
      display.innerHTML = displayArray;
      if (!displayArray.includes(".")) {
          displayArray += ".";
          displayArray = display;
      }

I have experimented with various solutions, but I'm still unable to resolve this.

I am looking to have a single dot, without the current issue where there is ",." added with each dot click

I understand that the problem lies within working with arrays, splitting the array, or similar operations, but I am struggling to pinpoint the exact issue.

Answer №1

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Calculator Application</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>


  <script src="script.js"></script>



    <table class="main" id="gradient">
      <tr class="row">
        <th class="column displayValue" id="display">0</th>
      </tr>
      <tr class="row">
        <th class="buttons bckbtn" onclick="clearAll()">Clear</th>
        <th class="buttons bckbtn" onclick="backbutton(this)">Backspace</th>
      </tr>
      <tr class="row">
        <th class="buttons" onclick="numbers(this)">7</th>
        <th class="buttons" onclick="numbers(this)">8</th>
        <th class="buttons" onclick="numbers(this)">9</th>
        <th class="buttons">/</th>
      </tr>
      <tr class="row">
        <th class="buttons" onclick="numbers(this)">4</th>
        <th class="buttons" onclick="numbers(this)">5</th>
        <th class="buttons" onclick="numbers(this)">6</th>
        <th class="buttons">x</th>
      </tr>
      <tr class="row">
        <th class="buttons" onclick="numbers(this)">1</th>
        <th class="buttons" onclick="numbers(this)">2</th>
        <th class="buttons" onclick="numbers(this)">3</th>
        <th class="buttons" onclick="numbers(this)">-</th>
      </tr>
      <tr class="row">
        <th class="buttons" id="decimal" onclick="dec(this)">.</th>
        <th class="buttons" onclick="numbers(this)">0</th>
        <th class="buttons" onclick="numbers(this)">=</th>
        <th class="buttons" onclick="numbers(this)">+</th>
      </tr>
    </table>


  </body>
</html>



function numbers(el) {

  let display = document.getElementById('display');

  if (display.innerHTML === "0") {
   display.innerHTML = "";
   display.innerHTML += el.innerHTML;
  }
  else {
    display.innerHTML += el.innerHTML;
  }
}


function clearAll() {

  let display = document.getElementById('display');
  display.innerHTML = "0";

}


function backbutton(b) {

  let display = document.getElementById('display');
  let value = display.innerHTML;
  let newValue = value.substr(0, value.length - 1);
  display.innerHTML = newValue;
  if (display.innerHTML === "") {
    display.innerHTML = "0";
  }
  document.getElementById("decimal").setAttribute("onclick", "dec(this)");

}


function dec(d) {

  let display = document.getElementById('display');
  let displayArray = display.innerHTML.split("");
  displayArray.join("") += d.innerHTML;
  display.innerHTML = displayArray;
  if (!displayArray.includes(".")) {
      displayArray += ".";
      displayArray = display;
  }

}

Answer №2

The issue lies in the concatenation of an array with a string

displayArray += d.innerHTML;

By default, converting an array to a string will join all elements with a ','

If you need a different separator, you must specify it

let array = [1,2,3,4]
console.log(array+'')
console.log(array.join())
console.log(array.toString())
//The correct approach
console.log(array.join(''))

Therefore, your code should be

displayArray = displayArray.join('') + d.innerHTML;

Keep in mind that displayArray will no longer be an Array, but rather a String

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mongoose's hook function is effective in the pre-stage but ineffective in the post-stage

When using Mongoose hooks, I aim to automatically change the status property to false if the outstandingBalance property has a value of zero. Although attempting to achieve this with Mongoose's PRE hook works, it requires re-invoking the request afte ...

Processing an HTML form submission with the help of PHP and AJAX

Having trouble saving basic email data from a website to a MySQL database. I've written the code, but it's not functioning correctly and I can't seem to figure out why. <form class="subfield"> <input type="text" id="em ...

How can you reset a variable counter while inside a forEach loop?

I am currently working on resetting a counter that is part of a recursive forEach loop within my code. Essentially, the code snippet provided calculates the length of the innermost key-value pair as follows: length = (key length) + (some strings inserted) ...

Having trouble with the Keydown event - the image isn't moving as expected

Something seems off with my code. I have an image displayed on a canvas, but when I press the specified key, nothing happens. Can you help me figure out where I went wrong? let img = document.getElementById("ship"); let player = { x: 375, ...

I am experiencing an issue with my d3 force directed graph where the links are not

I am relatively new to d3 and have limited experience with web frontend development. In my current web application project, I am attempting to create a force directed graph. Despite spending several hours trying to make it work, I have been unable to displ ...

How can I create a Discord bot command that ignores case sensitivity?

I wrote a custom "roleinfo" command for my Discord bot, but I'm struggling to make the role search case insensitive. Here is the code snippet: const Discord = require("discord.js"); module.exports.run = async (bot, message, args) => { //Me ...

The automation script for Playwright/Puppeteer is having trouble properly handling `async...await` in a `for..loop` on the `/signup` page

Currently, I am faced with the challenge of automating rate-limit requests using a playwright automation script. The issue arises when the script keeps attempting to sign up with the email <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data ...

Show the Form Data in a Stylish Bootstrap Popup

Our website's homepage features a basic form that sends its results to a page named Results.aspx. Instead of displaying the form results on the same page, I want them to appear in a new modal window. How can this be done? Just to summarize, the form ...

Unable to customize the button color within the Bootstrap framework

This button was created using Bootstrap. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <lin ...

Is a Singleton really necessary for my situation?

I am currently developing a Firefox extension that requires keeping multiple windows synchronized with the same information. The toolbar in each window queries a remote server periodically, but since Firefox windows are isolated environments with their own ...

What is the best way to use jQuery to emphasize specific choices within an HTML select element?

Seeking help with jQuery and RegEx in JavaScript for selecting specific options in an HTML select list. var ddl = $($get('<%= someddl.ClientID %>')); Is there a way to utilize the .each() function for this task? For Instance: <select i ...

Error: Unable to access the 'rotation' property of an undefined object in the animate function on line 266 of index.html, at line 287 of index.html

I am facing an error when trying to animate a model with rotation or position in my code. I attempted to create an init function to run everything, but it did not resolve the issue. The error only appears during animation; once the animation stops, the e ...

express-validator never accepts valid input

Currently, I am working on a project using the most recent version of nodejs and express. The basic site setup is complete, and now I am focusing on implementing user authentication based on what I've learned from this course. However, no matter what ...

When the status is set to "Playing," the Discord Audio Player remains silent

So, I'm in the process of updating my Discord audio bot after Discord made changes to their bot API. Despite my best efforts, the bot is not producing any sound. Here's a snippet of the code that is causing trouble: const client = new Discord.Cl ...

Maximizing Efficiency: Utilizing a Single Panel across Multiple HTML Files with jQueryMobile

Can a panel defined in index.html be used on another page, such as results.html? Or do I have to define the panel on every page and duplicate the HTML code on each page? Because I want the panel to be consistent across all pages. This is the panel in my ...

display the entire calendar for the chosen month

I am currently using Foundation Datepicker and Full Calendar. My requirement is as follows: 1) When I select a date in the calendar, For example, let's say it's July 2016. If I choose a date in November or any other month in the Foundation Date ...

Toggle between different socket.io servers for seamless connectivity

I'm looking for help with a situation where I need a socket.io client to connect to server A, disconnect, and then connect to server B. Any ideas on how I can achieve this? Thanks in advance! UPDATE: Attached below is the code snippet that's gi ...

When transferring JavaScript Array via Ajax to PHP, it results in a null response

I am attempting to send a JavaScript array to PHP, but the post data keeps returning null. Here is my JavaScript code: console.log($Seats); console.log($Seats.toString()); console.log(JSON.stringify({ $Seats })); var jsonStr = JSON.stringify($Seats); $.a ...

The transition effect of changing opacity from 0 to 1 is not functioning properly in Firefox

Having some trouble with this animation not working in Firefox. I'm triggering the animation using JavaScript after a delay like so: document.getElementById('my_id').style.webkitAnimationPlayState = "running"; I've also attempted: s ...

I'm having trouble adding a background image, even though I have set it to static. What could be

I attempted to add a background image to my Django website, but unfortunately, it was not successful. I followed the steps provided in this Stack Overflow answer here, however, it did not work. I even made changes to the database by migrating them, but s ...