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

Utilizing a function from a library in an Object within a Typescript environment

Currently, I am working on assigning a field within my interface to a function from an external library in the following manner: import { Accelerometer, } from 'expo-sensors'; type SensorInterface = { permChecker: () => Promise<Permiss ...

To prevent the default alignment in case the text exceeds the input length, stop the automatic alignment

I have a query regarding an input field with a maximum length of 4 characters. The appearance is such that these 4 characters seem to be delineated by borders which are actually 3 lines displayed above the input field. When I enter the fourth character, a ...

Adding data from PHP into a designated div element

update: After some trial and error, I managed to find a solution using jQuery and append() methods. From my PHP code, I created an array containing all the necessary information that I wanted to insert into the tab divs. I then encoded this array into JSON ...

Unusual activity observed in HTML5 contenteditable functionality

Within a list item, I have a span element. <ul> <li>text part 1 <span class="note">this is a note</span> text part 2 </li> <li>text part 3</li> </ul> When you double click on th ...

Tips on causing JavaScript execution to halt until an element has finished rendering

test.view.js timeDBox = new sap.ui.commons.DropdownBox({layoutData: new sap.ui.layout.GridData({linebreak: true}), change: function(oEvent){ oController.getKeyEqChart(); }, }), new sap ...

AJAX: Displaying the contents of a folder. Issue with URL resolution

I'm attempting to showcase a collection of images stored in a specific folder within a div. My approach involves utilizing AJAX within a JavaScript file titled edit, which is positioned one directory away from the index route. This implementation is b ...

Encountering an unexpected error: receiving a void element tag as input in React

Any ideas on how to resolve the following error message: input is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML` Check out my code snippet below: import "./styles.css"; export default function App() { re ...

Guide to automating tests on MAC using Protractor with Appium and IOS-Simulator

Is there a way to run automated tests using Protractor (or WebDriverJS) on a MAC with Appium and the IOS Simulator? We have been unsuccessful in running tests with the following configuration file, although it works fine with Selenium 2.0 - WebDriver. He ...

What is the process for redirecting to a different URL when the button is clicked?"

I am trying to display Home.js at localhost/posts, but when the button is clicked, it displays information at the auth.js URL. How can I link the button so that if the login information is correct, it redirects to "localhost/posts" instead of rendering its ...

How to obtain the height of the parent screen using an iframe

Imagine a scenario where a div contains an image that is set to perfectly fit the height of the screen. This setup works flawlessly, with one exception - when placed within an iframe, the height of the div adjusts to match the content's height rather ...

What are the consequences of submitting a form to a different website through POST method?

Dealing with a CMS that does not offer an easy way to add a NodeJS route for handling form data can be quite challenging. I'm considering the following setup - would this be considered bad practice or unsafe? Server 1 (Ghost CMS) : www.domain.com &l ...

Creating a banner image that scrolls while maintaining a fixed size

I'm looking to add a banner image with a scrolling effect as users navigate down the page, but I'm not sure what this technique is called. An example of what I'm trying to achieve can be seen on this site. As the user scrolls down, the res ...

Modifying the scope variable does not trigger an update in the AngularJS directive

Recently, I created a small directive that wraps its contents with another template file. The objective is to transform the code like this: <layout name="Default">My cool content</layout> into this output: <div class="layoutDefault">My ...

Mastering the utilization of custom input events in PrimeNG with Angular

I am currently working on an Angular 16 project. Within this project, I have implemented a number input field that is being validated using formControls. To make my work more efficient, especially since this input is used frequently, I decided to encapsula ...

One approach to animating elements on a web page is by utilizing Node.js

Imagine you want to programmatically define animated movement for elements on a web page. In JavaScript, this can be achieved using techniques outlined in this helpful guide: How TO - JavaScript HTML Animations. But how would you do this in Node.js? UPDAT ...

Ways to verify a correct email address using ReactJS

I'm currently working on a project using React.js and Next.js. I'm encountering an issue with handling the Axios response in Next.js as it's displaying "[object Object]" instead of the actual response data. How can I properly handle the resp ...

Dynamic Lookup Material Table

I am currently using MaterialTable imported from "material-table". import MaterialTable from "material-table" I am attempting to make the 'lookup' for an editable table dynamic. My goal is to have a drop-down with edit options when I make change ...

A customizable JavaScript NPM Package designed to specifically escape XML special characters while preserving the integrity of the XML tags

Seeking recommendations for a JavaScript npm package that can escape the values in an XML document while preserving the XML tags. Ideally, looking for a solution that only allows letters A-Z (upper and lower case), digits 0-9, and spaces within the value ...

Using the keyof lookup in a Typescript interface is a powerful way to

I'm looking for a solution similar to: interface Operation<T, K extends keyof T> { key: keyof T; operation: 'add' | 'remove'; value: T[K]; } but without the necessity of passing K as a template. Essentially, I want to ...

ways to halt a noise once an animation is complete

I don't have much experience with coding in general, but somehow I've made it this far. Now I'm stuck on the final piece of the puzzle. This is related to a Twitch alert that I'm setting up through 'Stream Elements'. The iss ...