16

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 Answers 2

45

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

Sign up to request clarification or add additional context in comments.

2 Comments

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...!
I agree, except that parseFloat doesn't have the radix parameter. It is just parseFloat(string).
7
leftVal = Math.floor(frequencyValue/30 + 0.5);

4 Comments

This looks wrong. Floor returns the lower value always, which is specifically what the questioner didn't want.
Ah, I see. A rather hackerish way of doing it, but ok.
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".
Math.round use the round to even convention, which in most cases is a bit weird, this does standard mathematical rounding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.