Split decimal variable into integral and fraction parts
Asked Answered
H

5

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?

Haddix answered 22/5, 2012 at 12:38 Comment(3)
A better approach may be not to use a decimal at all, but use an int/long representing "your value multipled by 100".Elseelset
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.Carolyncarolyne
Following answer of a similar question may suits those needs for fractional part: https://mcmap.net/q/187925/-get-the-decimal-part-from-a-doubleFriedafriedberg
S
31
       decimal fraction = (decimal)2.78;
        int iPart = (int)fraction;
        decimal dPart = fraction % 1.0m;
Stupor answered 30/4, 2015 at 9:35 Comment(4)
Very good use of modulus operator on decimal. I did not expect this to work, but it does beautifully (and it's fast) :)Molliemollify
I second @GoneCoding but the OP mentions "both parts should be integers".Intisar
@GeroldBroserreinstatesMonica Regarding the dPart variable, you can simply cast it as integer.Ginger
Not working if integer part is bigger that Int32.MaxValueTrigeminal
A
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.

Aspectual answered 27/1, 2014 at 14:13 Comment(2)
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)Articular
@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 typeAspectual
T
3
decimal fraction = doubleNumber - Math.Floor(doubleNumber) 

or something like that.

Tacye answered 8/6, 2015 at 13:38 Comment(0)
E
2

How about:

int fraction = (int) ((decimalValue - integral) * 100);
Emmett answered 22/5, 2012 at 12:42 Comment(0)
P
1

For taking out fraction you can use this solution:

Math.ceil(((f < 1.0) ? f : (f % Math.floor(f))) * 10000)
Proposal answered 24/6, 2015 at 1:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.