I have a float variable and would like to get only the part after the comma, so if I have 3.14. I would like to get 14 as an integer. How can I do that?
Here's another version that also tells how many digits are part of the fractional make-up, which I needed.
public static int GetFractionalPartAsInt(decimal n, out int numOfFractionalDigits)
{
n -= Math.Truncate(n);
n = Math.Abs(n);
int numOfFractionalDigitsValue = 0;
// When n != Math.Truncate(n), we have seen all fractional decimals.
while (n != Math.Truncate(n))
{
n *= 10;
numOfFractionalDigitsValue++;
}
numOfFractionalDigits = numOfFractionalDigitsValue;
return (int)n;
}
It's similar in idea to David's answer (his non-cheating version). However, I used the decimal type instead of double, which slows things down, but improves accuracy. If I convert David's (again, non-cheating version) answer to use a decimal type (in which case his "precision" variable can be changed to the constant zero), my answer runs about 25% faster. Note that I also changed his code to provide the number of fractional digits in my testing.