-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.

1
  • There's likely no reason to parseFloat(), and likely good reasons not to. Note that "4" * "3" == 12 Commented Feb 15, 2014 at 6:05

4 Answers 4

3
var num=4.5960797;
var n=num.toFixed(5);
Sign up to request clarification or add additional context in comments.

Comments

2

Try using toFixed:

var result = ((parseFloat(value1) * parseFloat(value2)) + (parseFloat(value3))) / (parseFloat(value2));
document.getElementById('result').innerHTML = result.toFixed(5);

Comments

0

Use Math.round(num * 100000) / 100000

1 Comment

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.
0
var result=Math.round(yourValue*100000)/100000

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.