View Full Version : Rounding to .5
jtbatt
04-14-2003, 11:50 PM
How would I round to the next highest .5?
Spookster
04-14-2003, 11:56 PM
You can use the round function:
http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/math.html#1197725
missing-score
04-15-2003, 12:16 AM
I think he wants to round a number to the nearest 0.5, just a quick go, but...
var num = 14.5443;
var sp = num.split('.');
if(sp[1] >= 0.25 && sp[1] < 0.75)
{
number = (Math.ceil(num)-0.5);
}
elseif(sp[1] < 0.25)
{
number = Math.floor(num);
}
elseif(sp[1] >= 0.75)
{
number = Math.ceil(num);
}
That might work, just quickly written tho. :D
cheesebagpipe
04-15-2003, 12:18 AM
<html>
<head>
<script type="text/javascript" language="javascript">
Number.prototype.roundUpByHalf = function() {
var n = Math.round(this);
return (n < this) ? n + .5 : Math.ceil(this);
}
var x = 2.33;
alert(x + ' --- ' + x.roundUpByHalf());
var x = 87.88;
alert(x + ' --- ' + x.roundUpByHalf());
var x = 5.00;
alert(x + ' --- ' + x.roundUpByHalf());
</script>
</head>
<body>
</body>
</html>
liorean
04-15-2003, 05:08 PM
For the easiest possible way, try:var nRounded=Math.round(2*num)/2;I suggest adding a method to the Number object instead, though.Number.prototype.round=function(nPrecision){
return (nPrecision*Math.round(this/nPrecision));
}
jtbatt
04-15-2003, 09:53 PM
Hey, thanks for all the quick help on this. Looks like I've got several ways to try. I appreciate it.
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.