31

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
invarbrass
  • 2,023
  • 4
  • 20
  • 23
  • A better approach may be not to use a decimal at all, but use an `int`/`long` representing "your value multipled by 100". – Rawling May 22 '12 at 12:48
  • Beware of unusual values. The max value for a decimal is ~7.9e28. The max value for an int is ~2e9 (significantly smaller). Even long only goes to ~9e18. So if you know the value will always be >= 0 you can use a ulong which goes all the way to ~18e18, giving a bit more leeway. – Davio May 22 '12 at 13:02
  • Following answer of a similar question may suits those needs for fractional part: http://stackoverflow.com/a/13038524/1178314 – Frédéric Apr 28 '14 at 10:19

5 Answers5

31
       decimal fraction = (decimal)2.78;
        int iPart = (int)fraction;
        decimal dPart = fraction % 1.0m;
Girish Sakhare
  • 743
  • 7
  • 14
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.

SOReader
  • 5,697
  • 5
  • 31
  • 53
  • Try to use this: var FileMinorPartClient = (int)(100.0m * (clientFileVersion - Math.Floor(clientFileVersion))); I get: "Operator '*' cannot be applied to operands of type 'decimal' and 'double'" (clientFileVersion is a double, a la 1.4) – B. Clay Shannon-B. Crow Raven Feb 19 '14 at 21:46
  • 1
    @B.ClayShannon It says so because you cannot mix those two. Either change `100.0m` to `100.0` or make sure `decimalValue` is of `decimal` type – SOReader Feb 19 '14 at 22:31
3
decimal fraction = doubleNumber - Math.Floor(doubleNumber) 

or something like that.

Stonz2
  • 6,306
  • 4
  • 44
  • 64
OMARY
  • 31
  • 1
2

How about:

int fraction = (int) ((decimalValue - integral) * 100);
Barry Kaye
  • 7,682
  • 6
  • 42
  • 64
1

For taking out fraction you can use this solution:

Math.ceil(((f < 1.0) ? f : (f % Math.floor(f))) * 10000)
Community
  • 1
  • 1
Aamol
  • 1,149
  • 1
  • 15
  • 23