Colin G Posted March 25, 2019 Share Posted March 25, 2019 Was testing toFixed() in 'Tryit' , basically want to be able to input the number of decimal places to display in the output. Have been using this with "toExponential" in many pages with no issues, but seemed not to work with "toFixed". The code below can be swapped by changing the comment lines to test, so either you ask for the number of dp or it can be set by "var decPlaces". However now results seem erratic, it may or may not work in either method - the dp may be shown or it gets rounded to 6 and sometimes it work for the input dp or the declared dp?? Also does 'var num' not have to be declared as a 'new Number' to get the '.toXXX' methods or does declaring var = 1; automatically create a number object? Its like the dec places is sometimes being picked up as a number and sometimes not. <!DOCTYPE html> <html> <body> <p>Click the button to display the fixed number.</p> <input type="number" id="input99" size="5" value="2" /> // input number of decimal places <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var decPlaces = document.getElementById("input99"); // var decPlaces = 4; var num = 5.56789; var n = num.toFixed(decPlaces); // var n = num.toExponential(decplaces); document.getElementById("demo").innerHTML = n; } </script> </body> </html> Link to comment Share on other sites More sharing options...
justsomeguy Posted March 25, 2019 Share Posted March 25, 2019 You should validate the number. Since all data on a page is a string, you can use parseInt to get an integer from what they entered and use isNaN to validate that it converted correctly. Link to comment Share on other sites More sharing options...
Colin G Posted March 26, 2019 Author Share Posted March 26, 2019 "input99" is validated as type "number" Found the "var decPlaces = document.getElementById("input99"); " is missing the '.value' at the end, so result can be unpredictable . Have fixed it now, tested inputting number of decimal places as 3.99 and it still comes out as 3 dp, so must be some integer validation in the method providing it is sent an actual number. Fixed issue now in http://www.alchymy.com/Astrolab/cCalc/cCalc009TScope.html Thanks Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now