Golnaz Valizade
Golnaz Valizade

Reputation: 19

How can add decimal in calculator with javascript?

I need help with my decimal button in my calculator. Its working now somehow but i need to perfect it more and kinda don't know how. So if you know a way how to make it better please help. So if you know how to fix it please do. Thank you.

  1. How can add decimal in printOutput

  2. The issue is when i press number and after i press decimal it works for example 2.34 but the problem is you can press decimal after every number making it for example 2.3.4 and thats not what i want.

this is a javascript code >>>>>>>

function getHistory() {
  return document.getElementById("history-value").innerHTML;
}
function printHistory(num) {
  document.getElementById("history-value").innerHTML = num;
}
function getOutput() {
  return document.getElementById("output-value").innerHTML;
}
function printOutput(num) {
  if (num == "") {
    document.getElementById("output-value").innerHTML = num;
  } else {
    document.getElementById("output-value").innerHTML = getFormatNumber(num);
  }
}

function getFormatNumber(num) {
  if (num == "-") {
    return "";
  }
  if (num.length > 10) {
    num = num.substr(0, 10);
    alert("it tooo much!");
  }
  var n = Number(num);
  if (n === "Infinity") {
    value = "0";
    alert("Error");
  } else {
    var value = n.toLocaleString("en");
  }
  return value;
}

function reverseNumberFormat(num) {
  return Number(num.replace(/,/g, ""));
}

let operator = document.getElementsByClassName("operator");
for (let i = 0; i < operator.length; i++) {
  operator[i].addEventListener("click", function () {
    if (this.id == "clear") {
      printOutput("");
      printHistory("");
    } else if (this.id == "backspace") {
      let output = reverseNumberFormat(getOutput()).toString();
      if (output) {
        output = output.substr(0, output.length - 1);
        printOutput(output);
      }
    } else {
      let output = getOutput();
      let 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 == "=") {
          let result = eval(history);
          printOutput(result);
          printHistory("");
        } else {
          history = history + this.id;
          printHistory(history);
          printOutput("");
        }
      }
    }
  });
}

let number = document.getElementsByClassName("number");
for (let i = 0; i < number.length; i++) {
  number[i].addEventListener("click", function () {
    let output = reverseNumberFormat(getOutput());
    if (output != NaN) {
      output += this.id;
      printOutput(output);
    }
  });
}
      <div id="calculator">
        <div id="result">
          <div id="history">
            <p id="history-value"></p>
          </div>
          <div id="output">
            <p id="output-value"></p>
          </div>
        </div>

        <div id="keyboard">
          <button class="operator" id="clear">C</button>
          <button class="operator" id="backspace">CE</button>
          <button class="operator" id="%">%</button>
          <button class="operator" id="/">&#247;</button>

          <button class="number" id="7">7</button>
          <button class="number" id="8">8</button>
          <button class="number" id="9">9</button>
          <button class="operator" id="*">&times;</button>

          <button class="number" id="4">4</button>
          <button class="number" id="5">5</button>
          <button class="number" id="6">6</button>
          <button class="operator" id="-">-</button>

          <button class="number" id="1">1</button>
          <button class="number" id="2">2</button>
          <button class="number" id="3">3</button>
          <button class="operator" id="+">+</button>

          <button class="number zero" id="0">0</button>
          <button class="operator" id=".">.</button>
          <button class="operator" id="=">=</button>
        </div>
      </div>
    </div>

Upvotes: 1

Views: 2442

Answers (2)

akhilkrishnan1268
akhilkrishnan1268

Reputation: 135

this is the solution for the "problem is you can press decimal after every number making it for example 2.3.4 and thats not what i want".If you simply want to avoid multiple decimals it can be used.

function printOutput(num) {
  if (num == "") {
    document.getElementById("output-value").innerHTML = num;
  } else {
    document.getElementById("output-value").innerHTML = getFormatNumber(num,document.getElementById("output-value").innerHTML);//since i want to check with the current value
  }
}
function getFormatNumber(num,prev_value) {
 const split_prev_value = prev_value.split(""); //this will give your string into ['s','t','r'...]
 if(split_prev_value.some((ele)=>ele==='.')){ //checking that if "." already exists in the prev_value and return empty string if already exists
  return "";
 }
 else{
  return ".";
 }
}

Upvotes: 0

GNETO DOMINIQUE
GNETO DOMINIQUE

Reputation: 677

Some change are necessary

First (1) : Change dot . operator className to number as illustrated below

<button class="number" id=".">.</button>

Second (2): In getFormatNumber replace it with this update .

function getFormatNumber(num) {
  if (num == "-") {
    return "";
  }
  if (num.length > 10) {
    num = num.substr(0, 10);
    alert("it tooo much!");
  }

  // to check whether a dot is placed just a the end of num like 6.
  let lastIndexOfDot  = num.toString().lastIndexOf(".") ; 
  let isDotted  =lastIndexOfDot  == false ? false: lastIndexOfDot == num.length-1 ? true : false ; 

  var n =  Number(num); 

  if (n === "Infinity") {
    value = "0";
    alert("Error");
  } else {
    var value = n.toLocaleString("en");
  }
   // if dotted is true then value has a dot at the end like : 5. so we return value  with its dot 
   if (isDotted ) return value +"." ; 

   return value;  // no dot at the end 
}

-Third (3 ) In handler of all element belonging to class number replace it with this new event handler

let number = document.getElementsByClassName("number");
for (let i = 0; i < number.length; i++) {
  number[i].addEventListener("click", function () {
    let output = reverseNumberFormat(getOutput());

    if (output != NaN ) {
      output += this.id;  
      // CHECK HERE IF output is already a valid decimal number 
      let matchCount = output.match(/\./g) ;
    
      if( matchCount && matchCount.length > 1 ) return  ; // => already decimal number 
      printOutput(output);
   }

 });
}

Four in (4) in reverseNumberFormat function replace it with this

function reverseNumberFormat(num) {
  return num.replace(/,/g, "");  // => Nb: conversion not necessary
}

NB: It is helpfull and It works on my side but don not hesitate to inform me for any bug or problem in the future .

Upvotes: 1

Related Questions