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
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);
}
}
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
}
}
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.
Using modulus will work:
if(num % 1 != 0) do something!
// eg. 23.5 % 1 = 0.5
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
}
I use this c function for objective c
BOOL CGFloatHasDecimals(float f) {
return (f-(int)f != 0);
}