Skip to main content
Inspiring
January 23, 2008
Question

rounding numbers up or down on decimal integrer

  • January 23, 2008
  • 1 reply
  • 437 views
Hi,
I have a challenging issue because Math.ceil and Math.floor rounds numbers to a whole number.

I am creating a dosage calculator and unfortunately I need to follow and produce existing values present on a printed sheet where the rounding does not happened in a straightforward manner. So I need to be able to round the numbers up or down in order to match existing values on the printed data sheet.

In one case, I have 6.251 as a result and I need to round it up to 6.3
In another case, I have 52.508 as a result and I need to round it down to 52.5

How can I accomplish this?
Thank you in advance.
Attila



This topic has been closed for replies.

1 reply

January 23, 2008
roundTo = function(inputNumber:Number, decimalPoints:Number):Number{
var outputNumber:Number;
var offsetNumber:Number = Math.pow(10,decimalPoints);
outputNumber = Math.round(inputNumber * offsetNumber)/offsetNumber;
return outputNumber;
}

trace(roundTo(1/3,4));
trace(roundTo(2/3,5));
trace(roundTo(1/6,2));
trace(roundTo(22/7,0));
trace(roundTo(22/7,1));
reinhatAuthor
Inspiring
January 24, 2008
Thank you for the funcion with the formula. It works great but I do not follow exactly how it does it.
Could you post an explanation?
Thanks,
Attila
Participating Frequently
January 24, 2008
I was looking at doing the same basic thing, rounding to the nearest hundredth in my case. Here is what I came up with utilizing the division and multiplication assignment operators:

function rndHundredth(i){
var num:Number = i;
num *= 100;
num = Math.round(num);
num /= 100;
return num;
}

if you want to round to the nearest tenth just change it to:

function rndTenth(i){
var num:Number = i;
num *= 10;
num = Math.round(num);
num /= 10;
return num;
}

hope its useful