Solucionado (ver solução)
Solucionado
(ver solução)
2
respostas

[Projeto] Calculadora

Html:

<!DOCTYPE html>
<html lang="pt-br">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="calculator">
      <div class="result">0</div>
      <div class="buttons">
        <button class="cor-cinza">C</button>
        <button class="cor-cinza">±</button>
        <button class="cor-cinza">%</button>
        <button class="cor-laranja">÷</button>

        <button class="cor-cinza-claro">7</button>
        <button class="cor-cinza-claro">8</button>
        <button class="cor-cinza-claro">9</button>
        <button class="cor-laranja">×</button>

        <button class="cor-cinza-claro">4</button>
        <button class="cor-cinza-claro">5</button>
        <button class="cor-cinza-claro">6</button>
        <button class="cor-laranja">-</button>

        <button class="cor-cinza-claro">1</button>
        <button class="cor-cinza-claro">2</button>
        <button class="cor-cinza-claro">3</button>
        <button class="cor-laranja">+</button>

        <button class="cor-cinza-claro button-zero">0</button>
        <button class="cor-cinza-claro">,</button>
        <button class="cor-laranja">=</button>
      </div>
    </div>

    <script src="form.js"></script>
  </body>
</html>

css

 :root{
    --cor--de-fundo: #f7f7f7 ;
    --cor--de-fundo-calculadora: #464646;
    --cor--de-fundo-resultado: #fff;
    --cor--cinza: #585858 ;
    --cor--cinza-claro: #747474;
    --cor--laranja: #f2a43b ;
 }
 
 * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
 }

 body {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
    background-color: var(--cor--de-fundo);
 }

 .calculator {
    width: 18.7em;
    background-color: var(--cor--de-fundo-calculadora);
    border-radius: 10px;
    box-shadow: 0px 4px 4px #00000040;
    font-family: 'Times New Roman', Times, serif;
    overflow: hidden;
 }

 .result {
    height: 80px;
    padding: 20px;
    text-align: right;
    color: var(--cor--de-fundo-resultado);
    font-size: 3rem;
 }

.buttons{
    display: grid;
    grid-template-columns: repeat(4,1fr);
    grid-gap: 1px
}

.buttons button {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 60px;
    color: var(--cor--de-fundo-resultado);
    font-size: 2rem;
    font-weight: bold;
    border: none;
    outline: none;
    cursor: pointer;
}

.button-zero {
    grid-column: span 2;
}

.cor-cinza{
    background-color: var(--cor--cinza);
}

.cor-cinza-claro{
    background-color: var(--cor--cinza-claro);
}

.cor-laranja {
 background-color: var(--cor--laranja);
}

button :active {
    opacity: 0.9;
}
2 respostas

JavaScript

const result = document.querySelector(".result");
const buttons = document.querySelectorAll(".buttons button");

let currentNumber = "";
let firstOperand = null;
let operator = null;
let restart = false;

function updateResult(originClear = false) {
  result.innerText = originClear ? 0 : currentNumber.replace(".", ",");
}

function addDigit(digit) {
  if (digit === "," && (currentNumber.includes(",") || !currentNumber)) return;

  if (restart) {
    currentNumber = digit;
    restart = false;
  } else {
    currentNumber += digit;
  }

  updateResult();
}

function setOperator(newOperator) {
  if (currentNumber) {
    calculate();

    firstOperand = parseFloat(currentNumber.replace(",", "."));
    currentNumber = "";
  }

  operator = newOperator;
}

function calculate() {
  if (operator === null || firstOperand === null) return;
  let secondOperand = parseFloat(currentNumber.replace(",", "."));
  let resultValue;

  switch (operator) {
    case "+":
      resultValue = firstOperand + secondOperand;
      break;
    case "-":
      resultValue = firstOperand - secondOperand;
      break;
    case "×":
      resultValue = firstOperand * secondOperand;
      break;
    case "÷":
      resultValue = firstOperand / secondOperand;
      break;
    default:
      return;
  }

  if (resultValue.toString().split(".")[1]?.length > 5) {
    currentNumber = parseFloat(resultValue.toFixed(5)).toString();
  } else {
    currentNumber = resultValue.toString();
  }

  operator = null;
  firstOperand = null;
  restart = true;
  percentageValue = null;
  updateResult();
}

function clearCalculator() {
  currentNumber = "";
  firstOperand = null;
  operator = null;
  updateResult(true);
}

function setPercentage() {
  let result = parseFloat(currentNumber) / 100;

  if (["+", "-"].includes(operator)) {
    result = result * (firstOperand || 1);
  }

  if (result.toString().split(".")[1]?.length > 5) {
    result = result.toFixed(5).toString();
  }

  currentNumber = result.toString();
  updateResult();
}

buttons.forEach((button) => {
  button.addEventListener("click", () => {
    const buttonText = button.innerText;
    if (/^[0-9,]+$/.test(buttonText)) {
      addDigit(buttonText);
    } else if (["+", "-", "×", "÷"].includes(buttonText)) {
      setOperator(buttonText);
    } else if (buttonText === "=") {
      calculate();
    } else if (buttonText === "C") {
      clearCalculator();
    } else if (buttonText === "±") {
      currentNumber = (
        parseFloat(currentNumber || firstOperand) * -1
      ).toString();
      updateResult();
    } else if (buttonText === "%") {
      setPercentage();
    }
  });
});
solução!

Opa, Kawã! Tudo joia?

Parabéns pelo resultado na resolução do desafio, ficou ótimo!

Também agradeço por compartilhar seu código com os demais estudantes, com certeza vai ajudar nos estudos de todas as pessoas que estão aprendendo este mesmo assunto.

Continue mergulhando em tecnologia e se tiver dúvidas, conte com o fórum.

Abraços e bons estudos!