Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split decimal variable into integral and fraction parts

Tags:

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?

like image 781
invarbrass Avatar asked May 22 '12 12:05

invarbrass


People also ask

What is the integral part and the decimal part in a decimal?

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.

What is integral part in decimal fraction?

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.

How can I write a program to print the integer part and fractional part of a given number?

float f=254.73; int integer = (int)f; float fractional = f-integer; printf ("The fractional part is: %f", fractional);

How do you separate integers and decimals in Python?

Use the math. modf() method to split a number into integer and decimal parts, e.g. result = math. modf(my_num) .


2 Answers

       decimal fraction = (decimal)2.78;         int iPart = (int)fraction;         decimal dPart = fraction % 1.0m; 
like image 191
Girish Sakhare Avatar answered Dec 29 '22 06:12

Girish Sakhare


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.

like image 38
SOReader Avatar answered Dec 29 '22 04:12

SOReader