21

How can I check whether a float number contains decimals like 2.10, 2.45, 12382.66 and not 2.00 , 12382.00. I want to know if the number is "round" or not. How can I do that programmatically?

Sam Spencer
  • 8,492
  • 12
  • 76
  • 133
Sam
  • 227
  • 1
  • 2
  • 3

7 Answers7

61

Using modulus will work:

if(num % 1 != 0) do something!
// eg. 23.5 % 1 = 0.5
Himanshu
  • 12,071
  • 7
  • 46
  • 61
Knights
  • 1,467
  • 1
  • 16
  • 24
  • 5
    Great answer, but this will not work in [PHP](http://php.net/manual/en/language.operators.arithmetic.php): "Operands of modulus are converted to integers (by stripping the decimal part) before processing." – Daan Aug 24 '16 at 09:44
8

I use this c function for objective c

BOOL CGFloatHasDecimals(float f) {
    return (f-(int)f != 0);
}
Alex Markman
  • 1,450
  • 1
  • 13
  • 15
5

If you care only about two decimals, get the remainder by computing bool hasDecimals = (((int)(round(x*100))) % 100) != 0;

In generic case get a fractional part as described in this topic and compare it to 0.

Community
  • 1
  • 1
Eugene Mayevski 'Callback
  • 45,135
  • 8
  • 71
  • 121
  • 2
    This worked beautifully for me. I'm using Objective-C btw. As long as you know how many decimals you care about evaluating, this is simple and does the job. And you can modify it by by multiplying 10 by the power of how many decimal spots you care about, to replace the occurrences of "100" in the above sample, to make it even more flexible. – idStar Feb 26 '12 at 18:35
3

You could do this:

  float num = 23.345f;
  int intpart = (int)num;
  float decpart = num - intpart;
  if(decpart == 0.0f)
  {
    //Contains no decimals
  }
  else
  {
     //Number contains decimals
  }
Owen
  • 174
  • 1
  • 1
  • 9
2
import java.lang.Math;
public class Main {
    public static void main(String arg[]){
        convert(50.0f);
        convert(13.59f);

    }

    private static void convert(float mFloat){
        if(mFloat - (int)mFloat != 0)
            System.out.println(mFloat);
        else
            System.out.println((int)mFloat);
    }
}
Ashish
  • 43
  • 5
1

PHP solution:

function hasDecimals($x)
{
    return floatval($x) - intval($x) != 0;
}
Zsolti
  • 1,571
  • 1
  • 11
  • 22
0

In Scala you can use isWhole() or isValidInt() to check if number has no fractional part:

object Example {
  def main(args: Array[String]) = {

    val hasDecimals = 3.14.isWhole //false
    val hasDecimals = 3.14.isValidInt//false

  }
}
Dmytro Melnychuk
  • 2,285
  • 21
  • 23