I am trying to extract the integral and fractional parts from a decimal value (both parts should be integers):
decimal decimalValue = 12.34m; int integral = (int) decimal.Truncate(decimalValue); int fraction = (int) ((decimalValue - decimal.Truncate(decimalValue)) * 100); (for my purpose, decimal variables will contain up to 2 decimal places)
Are there any better ways to achieve this?
35 Answers
decimal fraction = (decimal)2.78; int iPart = (int)fraction; decimal dPart = fraction % 1.0m; 4Try mathematical definition:
var fraction = (int)(100.0m * (decimalValue - Math.Floor(decimalValue))); Although, it is not better performance-wise but at least it works for negative numbers.
2decimal fraction = doubleNumber - Math.Floor(doubleNumber) or something like that.
How about:
int fraction = (int) ((decimalValue - integral) * 100); 0For taking out fraction you can use this solution:
Math.ceil(((f < 1.0) ? f : (f % Math.floor(f))) * 10000)