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
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).
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 .
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With