tags:

views:

295

answers:

3

I have the following javascript code.

if( frequencyValue <= 30)
            leftVal = 1;
        else if (frequencyValue > 270)
            leftVal= 10;
        else 
            leftVal = parseInt(frequencyValue/30);

Currently if given the value 55 (for example) it will return 1 since 1< 55/30 < 2. I was wondering if there was a way to round up to 2 if the decimal place being dropped was greater than .5.

thanks in advance

+2  A: 

Use a combination of parseFloat and Math.round

Math.round(parseFloat("3.567")) //returns 4

[EDIT] Based on your code sample, you don't need a parseInt at all since your argument is already a number. All you need is Math.round

Chetan Sastry
from painful experience I would always recommend passing in the optional second param to force it to ten base: parseInt( myNum, 10 ) otherwise you can get in a whole world of debug pain when it tries converting strings that start with 0's etc which throw it all out into Hex mode and so on, a real head hurter...!
Pete Duncanson
I agree, except that parseFloat doesn't have the radix parameter. It is just parseFloat(string).
Chetan Sastry
+1  A: 
leftVal = Math.floor(frequencyValue/30 + 0.5);
cdm9002
This looks wrong. Floor returns the lower value always, which is specifically what the questioner didn't want.
C. Ross
That's why you add 0.5
cdm9002
And the +0.5 rounds it.
Nosredna
Ah, I see. A rather hackerish way of doing it, but ok.
C. Ross
Perfectly acceptable technique. This is how round is implemented. From javadoc's Math.round: "The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type int".
cdm9002
A: 

I think this will solve your problem

<html>
<body>
 <script language="javascript">
  var a = 55/30;
  alert(a.toFixed(0));
 </script>
</body>
</html>

This is a sample code. you can replace my values with your variables.

You can refer the w3schools doc on numbers here. It gives you all the available methods for numbers.

If you want to do more math operations you can use the inbuilt Math Object. You can find the reference here.

Arun P Johny