0

Building a calculator and I'm implementing cube roots and square roots, but when reversed by squaring them or cubing them respectively, it is off by a very small, but it is noticeable and ugly in the calculator when there are several zeros and a 1 after it. Any way to prevent this, but still make the calculator accurate.

        function click22() {
    if (vi === 0) {
        reactant = Math.sqrt(reactant); 
    } else if (vi !== 0 && tn === 0) {
        reactant2 = Math.sqrt(reactant2);
    } else if (vi !== 0 && tn !== 0) {
        reactantspec = Math.sqrt(reactantspec);
    }
}
function click23() {
    if (vi === 0) {
        reactant = Math.cbrt(reactant); 
    } else if (vi !== 0 && tn === 0) {
        reactant2 = Math.cbrt(reactant2);
    } else if (vi !== 0 && tn !== 0) {
        reactantspec = Math.cbrt(reactantspec);
    }
    }
        if (vi === 0 && reactant != "0"){
    document.getElementById('result').innerHTML = reactant;
} else if (vi > 1 && reactant2 != "" && tx === 0) {
    document.getElementById('result').innerHTML = reactant2;
} else if (vi > 1 && tx > 0) {
    document.getElementById('result').innerHTML = reactantspec;
}
}
Benn
  • 55
  • 1
  • 1
  • 8
  • 2
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Code-Apprentice Jun 18 '18 at 16:41
  • The problem is the exact same as when dividing and multiplying as shown in the linked question . – Code-Apprentice Jun 18 '18 at 16:41
  • So there is no way to stop it from displaying that way? – Benn Jun 18 '18 at 16:46
  • Sure there is. It just takes more work on your part than simply adding the result to the HTML output directly. One solution is to simply round the output. – Code-Apprentice Jun 18 '18 at 16:50
  • One more question, for a calculator, do you even need to parsefloat the numbers? Is that necesarry – Benn Jun 18 '18 at 17:12
  • In order to do mathematical operations, you need a number. Most likely the input is originally a string instead, so yes, you need to call `parseFloat()` to parse the string to a float. – Code-Apprentice Jun 18 '18 at 17:22
  • I just removed all of the parsefloats in my calculator and it seems to work while running a string.. ? as in "4" * "5" – Benn Jun 18 '18 at 17:47
  • What happens when you do "4" + "5"? JavaScript has more lenient rules about converting data types, but you will get some unexpected behavior in some cases. – Code-Apprentice Jun 18 '18 at 19:15

0 Answers0