WebDeveloper.com

WebDeveloper.com (http://www.webdeveloper.com/forum/index.php)
-   JavaScript (http://www.webdeveloper.com/forum/forumdisplay.php?f=3)
-   -   Help with a rounding function (http://www.webdeveloper.com/forum/showthread.php?t=66386)

betheball 05-17-2005 03:01 PM

Help with a rounding function
 
I need a function that rounds a number up to the next 1000. For example, 493 would become 1000. 2006 would become 3000. I assume javascript has some built in math functions, but am not familiar with them. I would guess the best approach is to divide the number by 1000 and then multiply the whole number by 1000 and then if there was a remainder, add one more thousand. Can someone steer me in the right direction? The number will be entered into a textbox and the function will be called with an onclick event.

TheBearMay 05-17-2005 03:13 PM

This should be close:
Code:

<input type="text" id="rounder">
<button onclick="document.getElementById('rounder').value=nextK()">Round up</button>
<script type="text/javascript>
function nextK(){
var fullVal = document.getElementById("rounder").value;
var kVal=math.Floor(fullVal/1000)*1000;
var remVal=fullVal%1000;
if (remVal > 0) kVal+=1000;
return kVal;
}
</script>


nzakas 05-17-2005 03:15 PM

There are a few functions that do rounding in javascript:

Math.round() - rounds a number to the nearest 1.
Math.floor() - rounds a number down to the nearest 1.
Math.ceil() - rounds a number up to the nearest 1.

These are all meant to be used on floating point values and return integers. So what you actually want to do is use Math.ceil(), but translate your number into floating point. Try this:

Code:

function roundUp(iNumber) {
    var fNumber = iNumber / 1000;
    return Math.ceil(fNumber) * 1000;
}

var iClosest = roundUp(493);

SO if you pass in 493, it gets converted to 0.493. That number is then rounded up to 1 and multiplied by 1000 to get 1000.

betheball 05-17-2005 03:37 PM

Both seem to do the job. Thanks a lot!


All times are GMT -5. The time now is 12:09 AM.

Powered by vBulletin® Version 3.7.3
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.