Home > front end >  How to detect " " in JavaScript and convert it to a number?
How to detect " " in JavaScript and convert it to a number?

Time:10-25

I have a script like this

let x;
let y;
let z;
let obliczone;


document.getElementById("srednia").onclick = function() {
  x = document.getElementById("grade1").value;
  y = document.getElementById("grade2").value;
  z = document.getElementById("grade3").value;

  x = Number(x);
  y = Number(y);
  z = Number(z);
  obliczone = Number(obliczone);

  obliczone = (x   y   z) / 3;
  console.log(obliczone);
  document.getElementById("wynik").innerHTML = "Twoja średnia to "   obliczone;
}
<!DOCTYPE html>
<html lang="en">

<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">
  <link rel="stylesheet" href="main.css">
  <title>Document</title>
</head>

<body>
  <label>Ocena 1</label> <input type="text" id="grade1"><br>
  <label>Ocena 2</label> <input type="text" id="grade2"><br>
  <label>Ocena 3</label> <input type="text" id="grade3"><br>
  <label>Oblicz: </label> <button id="srednia">Średnia</button>

  <p id="wynik"></p>
  <script src="index.js"></script>
</body>

</html>

and if user type in a number with " " like 2 I want i to give me 2.5 value and if the input is higher than 6 to break the function. It meant to calculate arithmetic mean of 3 digits and as I wrote earlier it should change ex. 1 to 1.5

CodePudding user response:

By default when the JavaScript interpreter tries to cast the string to a number and this string contains a symbol it results in a NaN (Not a Number). You can do what you want by replacing the ' ' symbol with '.5'.

The new code:

  let x;
  let y;
  let z;
  let obliczone;


  document.getElementById("srednia").onclick = function () {
    x = document.getElementById("grade1").value;
    y = document.getElementById("grade2").value;
    z = document.getElementById("grade3").value;
    const doesXEndsWithPlus = x.endsWith(' ')
    const doesYEndsWithPlus = y.endsWith(' ')
    const doesZEndsWithPlus = z.endsWith(' ')
    if (doesXEndsWithPlus) x = x.replace(' ', '.5')
    if (doesYEndsWithPlus) y = y.replace(' ', '.5')
    if (doesZEndsWithPlus) z = z.replace(' ', '.5')
    x = Number(x);
    y = Number(y);
    z = Number(z);
    obliczone = Number(obliczone);

    obliczone = (x   y   z) / 3;
    console.log(obliczone);
    document.getElementById("wynik").innerHTML = "Twoja średnia to "   obliczone;
  }

CodePudding user response:

This is one way you can do it however if you end up putting more than 3 inputs it can start getting repetitive.

document.getElementById("srednia").onclick = function(){
   let obliczone;
   let x = document.getElementById("grade1").value;
   let y = document.getElementById("grade2").value;
   let z = document.getElementById("grade3").value;
   
   if (x.includes(' ')) {
      x = parseFloat(x.split(" ")[0]   ".5")
   }
   if (y.includes(' ')) {
      y = parseFloat(y.split(" ")[0]   ".5")
   }
   if (z.includes(' ')) {
      z = parseFloat(z.split(" ")[0]   ".5")
   }
   
    
    obliczone = (x y z) / 3;
    console.log(obliczone);
    document.getElementById("wynik").innerHTML = "Twoja średnia to "   obliczone; 
}

One solution to make it cleaner and more dynamic is to create a helper function formatNumInput(input):

function formatNumInput(input) {
   let newNum;
   if (input.includes(' ')) {
      newNum = parseFloat(input.split(" ")[0]   ".5")
   } else {
   newNum = parseFloat(input)
   }
   return newNum
}

document.getElementById("srednia").onclick = function(){
   let obliczone;
   let x = document.getElementById("grade1").value;
   let y = document.getElementById("grade2").value;
   let z = document.getElementById("grade3").value;
   
   x = formatNumInput(x)
   y = formatNumInput(y)
   z = formatNumInput(z)

   
    
    obliczone = (x y z) / 3;
    console.log(obliczone);
    document.getElementById("wynik").innerHTML = "Twoja średnia to "   obliczone; 
}

CodePudding user response:

I would like to propose you something a little bit different that could to inspired you and where are not you are not limited only to 3 values of ratings:

//here I define some globals variables
let evaluation = document.getElementById('eval');
let evaluations = [];
let showEval =  document.getElementById("evaluation");
let addEval = document.getElementById("addEval");
let average = 0

function showEvals (){
    for (let i = 0; i < evaluations.length; i  ) {
        showEval.innerHTML  = `<span>${evaluations[i]}</span>, ` 
    };
};// this is a function to show ratings

function countAverage () {
    let sum = 0
   for (let i = 0; i < evaluations.length; i  ) {
    const rating = parseFloat(evaluations[i],10)//here I convert a string go float (Numners() create variable type object not type number
       sum  = rating
       average = (sum/evaluations.length).toFixed(2)// I limited my float to 2 digits 
       
    };
    document.getElementById("result").innerHTML = "Twoja średnia to "   average
  } // this function counts and shows average

  addEval.onclick = function(){
    evaluations.push(evaluation.value)
    showEval.innerHTML = [];
    showEvals();
    countAverage();
};// here new rangs is pushed to the array of evaluations and it calls ather functions 
<!DOCTYPE html>
<html lang="en">
<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>
    <script src="script.js" defer></script>
</head>
<!DOCTYPE html>
<html lang="en">
<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>
    <script src="script.js" defer></script>
</head>
<body>
    <label for="eval">Dodaj ocene:</label>

    <select name="evals" id="eval">
        <option value="1">1</option>
        <option value="1.5">1 </option>
        <option value="2">2</option>
        <option value="2.5">2 </option>
        <option value="3">3</option>
        <option value="3.5">3 </option>
        <option value="4">4</option>
        <option value="4.5">4 </option>
        <option value="5">5</option>
        <option value="5.5">5 </option>
        <option value="6">6</option>
    </select>
</select>
<button id="addEval">Dodaj ocene</button>
<h2>Twoje oceny to:</h2>
<div id="evaluation"></div>

<p id="result"></p>

</body>
</html>

  • Related