Enjoy an ad free experience by logging in. Not a member yet? Register.

Results 1 to 3 of 3

07032017, 11:24 AM #1
 Join Date
 Jun 2017
 Posts
 3
 Thanks
 0
 Thanked 0 Times in 0 Posts
Rounding off numbers using Javascript
Hello, looking for some help if possible as whatever solution I try isnt working, and this is probably something so simple but its driving me up the wall now!
I have the following script:
Code:calculate = function() { var textInput = document.getElementById('textInput').value; var textInput2 = document.getElementById('textInput2').value; document.getElementById('Total1').value = parseInt(textInput)/parseInt(textInput2)/12; document.getElementById('Total2').value = parseInt(textInput)/100*103.83; } function show_value2(x) { document.getElementById("slider_value2").innerHTML=x; } function show_value3(x) { document.getElementById("slider_value3").innerHTML=x; }
I need to round these numbers up though (so this: 9723.538461538461 becomes this: 9723)
Thank you

07212017, 08:45 PM #2
 Join Date
 Apr 2017
 Posts
 4
 Thanks
 1
 Thanked 0 Times in 0 Posts
The code I try:
Code:<script type="text/javascript"> // 9723.538461538461 becomes this: 9723 var n = 9723.538461538461; var s= String(n); alert(s[0]); // 9 var A = [ ]; for(var i=0; s[i] != "."; i++) { A[i] = s[i]; } alert(A);//9,7,2,3 var t = A.join(""); // alert( t ); // 9723 // alert(typeof(t));// string t = Number(t); // alert(typeof(t)); // number // alert(t +4); // 9727 </script>

07222017, 08:03 PM #3
 Join Date
 Feb 2016
 Location
 Keene, NH
 Posts
 2,068
 Thanks
 2
 Thanked 297 Times in 287 Posts
What you are looking for is Math.round. Parseint is a truncate  equivalent to Math.floor
Also do you REALLY mean to truncate the user input?
but yeah, Math.round(1.56) gives you 2.
It's important to know all three: Math.round, Math.floor, and Math.ceil (ceiling)
Math.round(1.001) == 1
Math.round(1.5) == 2
Math.round(1.999) == 2
Math.floor(1.001) == 1
Math.floor(1.5) == 1
Math.floor(1.999) == 1
Math.ceil(1.001) == 2
Math.ceil(1.5) == 2
Math.ceil(1.999) == 2I would rather have questions that can't be answered, than answers that can't be questioned.
http://www.cutcodedown.com