0

I'm doing a multiplication using JavaScript. The given input is multiplied with 0.05.

The JavaScript multiples the given input number with 0.05 but it fails in the following aspect.

  1. The calculated value should stop at 2 decimal points. Example: 3284.40 instead of 3284.40000000000003
  2. Also, the old output should clear automatically when a new value is calculated.

decimal

<script>
    function doMath() {
    var numOne = document.getElementById('num1').value;
    var numTwo = document.getElementById('num2').value;
    var theProduct = 0.05 * parseInt(numTwo);
    var p = document.getElementById('theProduct');
    p.innerHTML += theProduct;
    document.getElmentById('doMath').innerHTML='';
    }
</script>
    <input id="num1"  type="hidden" name="num1"  value="0.05" readonly><br> Value:<br>
    <input id="num2" type="text" name="num2">
    <br><input type="button" value="Convert" onclick="doMath()" />
    </div><div id="theProduct">$</div>

If the value given is 5688 then I expect the output to be 3284.40, but the actual output is 3284.40000000000003

When I click "Convert" twice, I expect the output to be 3284.40, but the actual output is 284.40000000000003284.40000000000003

M.K.Dan
  • 1
  • 1
  • 2
    https://stackoverflow.com/questions/6134039/format-number-to-always-show-2-decimal-places Note: You will also want to clear your output div, so it does not keep appending – Josh Adams Jan 07 '19 at 18:42
  • How to clear the output everytime? – M.K.Dan Jan 07 '19 at 18:44

1 Answers1

0

For decimal points try this one

const myround = ( num, dec = 2 ) => Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);

Now to clean up the content then

document.getElementById( 'theProduct' ).innerHtml = '$';

To set the new content then

document.getElementById( 'theProduct' ).innerHtml = '$' + parseFloat( result );

where the result is what you get from your previous calculation

In case you need to sum it up with the previous result then

var el = document.getElementById( 'theProduct' );
el.innerHtml = '$' + parseFloat( el.innerHtml ) + result;

I'll let you do some tweaking and have some fun! :)

gmastro
  • 126
  • 3