Pressing a button to input a decimal in a calculator

I am encountering an issue with inputting decimals in my JavaScript. I have a function that checks if the output is Not a Number (NaN). If it is, I want it to output a decimal instead.

I attempted to add another conditional statement like this:

var operator = document.getElementsByClassName("operator");
for(var i =0;i<operator.length;i++){
    operator[i].addEventListener('click',function(){
        if(this.id=="clear"){
            printHistory("");
            printOutput("");
        }
        else if(this.id=="backspace"){
            var output=reverseNumberFormat(getOutput()).toString();
            if(output){
                output= output.substr(0,output.length-1);
                printOutput(output);
            }
        }
        else{
            var output=getOutput();
            var history=getHistory();
            if(output===""&&history!==""){
                if(isNaN(history[history.length-1])){
                    history= history.substr(0,history.length-1);
                }
            }
            if(output!=="" || history!==""){
                output= output===""?output:reverseNumberFormat(output);
                history=history+output;
                if(this.id=="="){
                    var result=eval(history);
                    printOutput(result);
                    printHistory("");
                }
                else{
                    history=history+this.id;
                    printHistory(history);
                    printOutput("");
                }
            }
        }

    });
}
var number = document.getElementsByClassName("number");
for(var i =0;i<number.length;i++){
    number[i].addEventListener('click',function(){
        var output=reverseNumberFormat(getOutput());
        if(output!=NaN){ 
            output=output+this.id;
            printOutput(output);
        } if (output=NaN){
            printOutput('.');
        }
    });
}

Answer №1

One approach is to utilize the isNan() function, a handy built-in tool. To further confirm that it is indeed not an Nan, you can employ parseFloat() which specifically verifies if it is a float rather than a string.

isNaN(parseFloat(output))

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

After removing an element from an array in Vue.js, how can we adjust its class to reflect the change?

Apologies for my lack of proficiency in English. I am eager to find a solution to resolve these issues. I am working on a todolist and encountering an issue where the class ('centerLine') continues to affect the next element after deleting an a ...

Tips on choosing a child element with a parameter in React

Is it possible to pass a parameter in my function and use it to select a child of my JSON parse? I want to create a function (checkMatch) that can check if a username in my database matches with the input value. It should return 1 if there is a match, oth ...

Utilize Node.js v16 for the execution of chaincode operations

Currently, I am executing JavaScript/TypeScript chaincode from fabric-samples (asset-transfer-basic/chaincode-javascript) and my requirement is to switch the Node.js version from 12 to 16. I suspect that the hyperledger/fabric-nodeenv image is specifying ...

Vue.js routing and mixin dilemma

Calling all Vue developers! I am currently working on a vuebnb tutorial and running into an issue with routing and mixins. I have attempted to assign data before entering the router using the beforeRouteEnter guard, but it seems like my template is being r ...

Issue with Angular-cli: typescript files not being generated when using the --dev option

Currently using angular-cli version 1.0.0-beta.14 with node version 6.6.0 on a Windows 32 bit x64 operating system. This setup utilizes the webpack version of angular-cli and I can successfully use ng build to compile. The output of ng build indicates that ...

Display a placeholder page during the processing of an asynchronous task by Express JS

Perhaps this issue is either too simple to be overlooked or too complex to tackle, but despite my efforts of over 3 hours searching for a solution, I am unable to find one. It seems like it should be a common problem and I am just too inexperienced to loca ...

When a single object is entered, JSON returns 'undefined', however, it works successfully when using the .map() function

Utilizing Axios to fetch data from DeezerAPI, I initially rendered information using .map() and everything worked smoothly when passing it to a Component. However, when attempting to access a single JSON object, I encountered an 'undefined' error ...

Using ReactJS to create different behavior for checkboxes and rows in tables with Material-UI

I am looking to customize the functionality of checkboxes and table rows. Currently, clicking on a row also clicks the checkbox, and vice versa. What I would like to achieve is for clicking on a row to trigger a dialogue box, and for clicking on the chec ...

Parent's hover element

I am currently working with the following loop: <?php if( have_rows('modules') ): $counter = 0; while ( have_rows('modules') ) : the_row(); ?> <div class="col span_4_of_12 <?php if($counter == 0) { ?>firs ...

Enhance the "content switcher" code

I have been working on improving my "contenthandler" function. It currently changes different articles when I click different buttons, which I am satisfied with. However, I believe there may be a better approach to this and would appreciate any advice on h ...

Are you familiar with Mozilla's guide on combining strings using a delimiter in Angular2+?

I found myself in need of concatenating multiple string arguments with a specific delimiter, so after searching online, I stumbled upon a helpful guide on Mozilla's website that taught me how to achieve this using the arguments object. function myCo ...

The ajax success error function does not trigger in jQuery

Hey, check out my code below: <html> <head> <script src="http://code.jquery.com/jquery-1.8.0.min.js"> </script> </head> <body> <form id="foo"> <label for="bar">A bar</label> <input id ...

Sending the HTML input value to a Knockout view

Can someone assist me with a dilemma I'm facing? Within CRM on Demand, I have a view that needs to extract values from CRM input fields to conduct a search against CRM via web service. If duplicate records are found, the view should display them. Be ...

Guide to automatically updating a table with AJAX requests

My task involves utilizing AJAX to request a random string consisting of 10 numbers from an asp page. The numbers must be delimited by "||" and displayed in a table format. The table is designed to showcase only the top 10 results, with each new row addin ...

Inadequate data being sent to the server from Angular2 post request

Currently, I have a form field whose value I am passing to a service as this.form.value. However, when I log this.form.value on the console, I see Object { email: "zxzx", password: "zxzxx" }. Despite this, when I send the same data to the service and make ...

Is it possible to set a different default page index other than 0 in a material table using reactjs?

I have noticed that the default page index in the material table is set to '0', but the API I am currently using begins with a page index of '1'. Is there a way to adjust the default page index of the table to match that of the API? ...

Asynchronous functions within the next context

Hello there! I am trying to send the client's IP address from the frontend in a Next.js application to the backend. To retrieve the IP, I am using the following function: async function getIP() { var clientIP = await publicIp.v4(); ...

Creating a global variable in Angular that can be accessed by multiple components is a useful technique

Is there a way to create a global boolean variable that can be used across multiple components without using a service? I also need to ensure that any changes made to the variable in one component are reflected in all other components. How can this be ac ...

An AngularJS project utilizing exclusively EJB

Can an AngularJS application be built directly with EJB without needing to expose them as REST services? Many examples on the internet show that eventually REST services are required to provide data to AngularJS. This means that EJB methods must be expos ...

Is it a mistake? Using React and ES6 without Babel may not be the

Have you ever considered bundling all of your classes into a single file without using Babel to polyfill it to ES5? If the browser doesn't support ES6, you could then use Babel in the browser or load the polyfilled bundle and manually add the dependen ...