8

How can I check if a number's decimal value is higher than .5 in JavaScript?

For example, I need to know if a number's decimal point is between .5 (higher) and .9 (equal or lower).

Some example numbers: 0.6, 2.7, 4.9.

Cofey
  • 11,144
  • 16
  • 52
  • 74
  • 1
    possible duplicate of [Get decimal portion of a number with JavaScript](http://stackoverflow.com/questions/4512306/get-decimal-portion-of-a-number-with-javascript) – Codeman Aug 05 '14 at 20:44

2 Answers2

15
var num = 5.7;

if((num % 1) > 0.5)
    console.write("remainder is greater than 0.5");
Codeman
  • 12,157
  • 10
  • 53
  • 91
5

Round the number and check whether the result is larger than the number:

n < Math.round(n)

Math.round rounds the number up if the decimal part is .5 or higher.

Note: The result will be true if the decimal part of the number is >= .5, not just > .5.

To account for precision errors, you probably would also have to floor n:

Math.floor(n) < Math.round(n)
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143