Check whether a float number contains decimals or not

前端 未结 7 2354
难免孤独
难免孤独 2020-12-29 07:02

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 th

相关标签:
7条回答
  • 2020-12-29 07:39
    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-29 07:40

    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
    
      }
    }
    
    0 讨论(0)
  • 2020-12-29 07:44

    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.

    0 讨论(0)
  • 2020-12-29 07:50

    Using modulus will work:

    if(num % 1 != 0) do something!
    // eg. 23.5 % 1 = 0.5
    
    0 讨论(0)
  • 2020-12-29 07:52

    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
      }
    
    0 讨论(0)
  • 2020-12-29 07:56

    I use this c function for objective c

    BOOL CGFloatHasDecimals(float f) {
        return (f-(int)f != 0);
    }
    
    0 讨论(0)
提交回复
热议问题