[c#] Get the decimal part from a double

I want to receive the number after the decimal dot in the form of an integer. For example, only 05 from 1.05 or from 2.50 only 50 not 0.50

This question is related to c# .net

The answer is


Updated Answer

Here I am giving 3 approaches for the same.

[1] Math Solution using Math.Truncate

 var float_number = 12.345;
 var result = float_number - Math.Truncate(float_number);

// input : 1.05
// output : "0.050000000000000044"

// input : 10.2
// output : 0.19999999999999929

If this is not the result what you are expecting, then you have to change the result to the form which you want (but you might do some string manipulations again.)

[2] using multiplier [which is 10 to the power of N (e.g. 10² or 10³) where N is the number of decimal places]

       // multiplier is " 10 to the power of 'N'" where 'N' is the number 
       // of decimal places
       int multiplier = 1000;  
       double double_value = 12.345;
       int double_result = (int)((double_value - (int)double_value) * multiplier);

// output 345

If the number of decimal places is not fixed, then this approach may create problems.

[3] using "Regular Expressions (REGEX)"

we should be very careful while writing solutions with string. This would not be preferable except some cases.

If you are going to do some string operations with decimal places, then this would be preferable

    string input_decimal_number = "1.50";
    var regex = new System.Text.RegularExpressions.Regex("(?<=[\\.])[0-9]+");
    if (regex.IsMatch(input_decimal_number))
    {
        string decimal_places = regex.Match(input_decimal_number).Value;
    }

// input : "1.05"
// output : "05"

// input : "2.50"
// output : "50"

// input : "0.0550"
// output : "0550"

you can find more about Regex on http://www.regexr.com/


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

double frac = value % 1;

It is very simple

       float moveWater =  Mathf.PingPong(theTime * speed, 100) * .015f;
       int    m = (int)(moveWater);
       float decimalPart= moveWater -m ;

       Debug.Log(decimalPart);

I guess this thread is getting old but I can't believe nobody has mentioned Math.Floor

//will always be .02 cents
(10.02m - System.Math.Floor(10.02m))

int last2digits = num - (int) ((double) (num /  100) * 100);

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


Use a regex: Regex.Match("\.(?\d+)") Someone correct me if I'm wrong here


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.


var result = number.ToString().Split(System.Globalization.NumberDecimalSeparator)[2]

Returns it as a string (but you can always cast that back to an int), and assumes the number does have a "." somewhere.


Better Way -

        double value = 10.567;
        int result = (int)((value - (int)value) * 100);
        Console.WriteLine(result);

Output -

56

 string input = "0.55";
    var regex1 = new System.Text.RegularExpressions.Regex("(?<=[\\.])[0-9]+");
    if (regex1.IsMatch(input))
    {
        string dp= regex1.Match(input ).Value;
    }

The simplest variant is possibly with Math.truncate()

double value = 1.761
double decPart = value - Math.truncate(value)

That may be overhead but should work.

double yourDouble = 1.05;
string stringForm = yourDouble.ToString();
int dotPosition = stringForm.IndexOf(".");
decimal decimalPart = Decimal.Parse("0" + stringForm.Substring(dotPosition));

Console.WriteLine(decimalPart); // 0.05

Here's an extension method I wrote for a similar situation. My application would receive numbers in the format of 2.3 or 3.11 where the integer component of the number represented years and the fractional component represented months.

// Sample Usage
int years, months;
double test1 = 2.11;
test1.Split(out years, out months);
// years = 2 and months = 11

public static class DoubleExtensions
{
    public static void Split(this double number, out int years, out int months)
    {
        years = Convert.ToInt32(Math.Truncate(number));

        double tempMonths = Math.Round(number - years, 2);
        while ((tempMonths - Math.Floor(tempMonths)) > 0 && tempMonths != 0) tempMonths *= 10;
        months = Convert.ToInt32(tempMonths);
    }
}

    public static string FractionPart(this double instance)
    {
        var result = string.Empty;
        var ic = CultureInfo.InvariantCulture;
        var splits = instance.ToString(ic).Split(new[] { ic.NumberFormat.NumberDecimalSeparator }, StringSplitOptions.RemoveEmptyEntries);
        if (splits.Count() > 1)
        {
            result = splits[1];
        }
        return result;
    }

Why not use int y = value.Split('.')[1];?

The Split() function splits the value into separate content and the 1 is outputting the 2nd value after the .


You may remove the dot . from the double you are trying to get the decimals from using the Remove() function after converting the double to string so that you could do the operations required on it

Consider having a double _Double of value of 0.66781, the following code will only show the numbers after the dot . which are 66781

double _Double = 0.66781; //Declare a new double with a value of 0.66781
string _Decimals = _Double.ToString().Remove(0, _Double.ToString().IndexOf(".") + 1); //Remove everything starting with index 0 and ending at the index of ([the dot .] + 1) 

Another Solution

You may use the class Path as well which performs operations on string instances in a cross-platform manner

double _Double = 0.66781; //Declare a new double with a value of 0.66781
string Output = Path.GetExtension(D.ToString()).Replace(".",""); //Get (the dot and the content after the last dot available and replace the dot with nothing) as a new string object Output
//Do something