-2

I am working on a calculator and would like it to round to about 5 decimal places. Here is my javascript code to get an inout and produce the output:

        <div class="input"> 
        Price paid per share: <input id="value1" type="text" /><br>
        Number of shares bought: <input id="value2" type="text" /><br>
        Commission/ fee's paid: <input id="value3" type="text" /><br>
        <center><input type="submit" class="submit"  onclick="output();"></center>  
    </div>
    <center><p class="result" id="result"> </p></center>

    <script type="text/javascript" language="javascript" charset="utf-8">
   function output(){
       var value1 = document.getElementById('value1').value;
       var value2 = document.getElementById('value2').value;
       var value3 = document.getElementById('value3').value; 
       document.getElementById('result').innerHTML = ((parseFloat(value1) * parseFloat(value2)) + (parseFloat(value3))) / (parseFloat(value2));
    }

Anyone know how I could round my output/ results to about 5 decimal places? Thanks.

ng150716
  • 2,195
  • 5
  • 40
  • 61
  • There's likely no reason to `parseFloat()`, and likely good reasons not to. Note that `"4" * "3" == 12` – Phrogz Feb 15 '14 at 06:05

4 Answers4

3
var num=4.5960797;
var n=num.toFixed(5);
SFIntegrator
  • 193
  • 1
  • 9
2

Try using toFixed:

var result = ((parseFloat(value1) * parseFloat(value2)) + (parseFloat(value3))) / (parseFloat(value2));
document.getElementById('result').innerHTML = result.toFixed(5);
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
0

Use Math.round(num * 100000) / 100000

Akshat Singhal
  • 1,801
  • 19
  • 20
  • This leaves the result as a number, and not a string, where floating point representations may later cause the string representation to be incorrect. Further, a value like `1` will show as `1` instead of `1.00000`. – Phrogz Feb 15 '14 at 06:04
0
var result=Math.round(yourValue*100000)/100000
ltalhouarne
  • 4,586
  • 2
  • 22
  • 31
  • 1
    This leaves the result as a number, and not a string, where floating point representations may later cause the string representation to be incorrect. Further, a value like `1` will show as `1` instead of `1.00000`. – Phrogz Feb 15 '14 at 06:03