0

I'm trying to give the outcome of this script 2 decimals. They all actually already have 2 decimals, but when I add the last 2 together (35.75 + 16.06), I get €51.629999999999995 as the output.

Here is my script;

<!DOCTYPE html>

<html>
  <head>
    <script>
      function bereken() {
        var total = 0;
        if (document.forms[0].boek1.checked)  {
          total += 27.74;
        }
        if (document.forms[0].boek2.checked) {
          total += 26.13;
        }
        if (document.forms[0].boek3.checked) {
          total += 35.57;
        }
        if (document.forms[0].boek4.checked) {
          total += 16.06;
        }
        totalP = "€" + total
        document.forms[0].total.value = totalP; 
      } 
    </script>

  </head>

  <body>
    <form>
      <input type="checkbox" name="boek1">Boek 1<br>
      <input type="checkbox" name="boek2">Boek 2<br>
      <input type="checkbox" name="boek3">Boek 3<br>
      <input type="checkbox" name="boek4">Boek 4<br>
      <div><input type="button" value="Totaal" onclick="bereken()" /><br><br>
        <input type="text" value="€" name="total" size="5" />
    </form>
  </body>

Does any of you know what I did wrong?

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252

2 Answers2

1

Use Math.round():

document.forms[0].total.value = Math.round(parseFloat(totalP.substr(1)) * 100)/100;

Working Preview

There are other ways to do it too. You can also use .toFixed(n):

document.forms[0].total.value = parseFloat(totalP.substr(1)).toFixed(2);
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round

checkout the function decimalAdjust. Works pretty well

function decimalAdjust(type, value, exp) {
    // If the exp is undefined or zero...
    if (typeof exp === 'undefined' || +exp === 0) {
      return Math[type](value);
    }
    value = +value;
    exp = +exp;
    // If the value is not a number or the exp is not an integer...
    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
      return NaN;
    }
    // Shift
    value = value.toString().split('e');
    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
    // Shift back
    value = value.toString().split('e');
    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
  }
Hassaan
  • 1,561
  • 1
  • 9
  • 15