Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

integer rounding with parseInt in javascript

Tags:

javascript

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

like image 504
ErnieStings Avatar asked Aug 04 '09 16:08

ErnieStings


People also ask

Does parseInt round in JavaScript?

parseInt() easily converts your string to a rounded integer. In these cases, simply define your string argument and set the radix to 10 (or if you have a special use-case, another numerical value).

How does parseInt () work?

Description. The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .

Why parseInt is not used more often in JavaScript?

parseInt() doesn't always correctly convert to integer In JavaScript, all numbers are floating point. Integers are floating point numbers without a fraction. Converting a number n to an integer means finding the integer that is “closest” to n (where “closest” is a matter of definition).

What do you mean by parseInt 4f 16?

The parseInt() function is used to accept the string ,radix parameter and convert it into an integer. The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.


1 Answers

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

like image 174
Chetan S Avatar answered Sep 20 '22 05:09

Chetan S