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?

3

5 Answers

 decimal fraction = (decimal)2.78; int iPart = (int)fraction; decimal dPart = fraction % 1.0m; 
4

Try 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.

2
decimal fraction = doubleNumber - Math.Floor(doubleNumber) 

or something like that.

How about:

int fraction = (int) ((decimalValue - integral) * 100); 
0

For taking out fraction you can use this solution:

Math.ceil(((f < 1.0) ? f : (f % Math.floor(f))) * 10000) 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.