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?
The integer part, or integral part of a decimal number is the part to the left of the decimal separator. (See also truncation.) The part from the decimal separator to the right is the fractional part.
The integer part or integral part of a decimal numeral is the integer written to the left of the decimal separator (see also truncation). For a non-negative decimal numeral, it is the largest integer that is not greater than the decimal.
float f=254.73; int integer = (int)f; float fractional = f-integer; printf ("The fractional part is: %f", fractional);
Use the math. modf() method to split a number into integer and decimal parts, e.g. result = math. modf(my_num) .
decimal fraction = (decimal)2.78; int iPart = (int)fraction; decimal dPart = fraction % 1.0m;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With