Get the decimal part from a double

var decPlaces = (int)(((decimal)number % 1) * 100);

This presumes your number only has two decimal places.


the best of the best way is:

var floatNumber = 12.5523;

var x = floatNumber - Math.Truncate(floatNumber);

result you can convert however you like


There is a cleaner and ways faster solution than the 'Math.Truncate' approach:

double frac = value % 1;

Solution without rounding problem:

double number = 10.20;
var first2DecimalPlaces = (int)(((decimal)number % 1) * 100);
Console.Write("{0:00}", first2DecimalPlaces);

Outputs: 20

Note if we did not cast to decimal, it would output 19.

Also:

  • for 318.40 outputs: 40 (instead of 39)
  • for 47.612345 outputs: 61 (instead of 612345)
  • for 3.01 outputs: 01 (instead of 1)

If you are working with financial numbers, for example if in this case you are trying to get the cents part of a transaction amount, always use the decimal data type.

Update:

The following will also work if processing it as a string (building on @SearchForKnowledge's answer).

10.2d.ToString("0.00", CultureInfo.InvariantCulture).Split('.')[1]

You can then use Int32.Parse to convert it to int.

Tags:

C#

.Net