117

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

9
  • 15
    2.50 is just 2.5. I assume you're talking of strings. Commented Oct 23, 2012 at 20:15
  • 3
    Are you always returning the first two digits after the decimal place? Is the input a decimal, float, string, ...?
    – Greg
    Commented Oct 23, 2012 at 20:16
  • 3
    An example of usages goes a long way toward getting quality answers, for next time.
    – tmesser
    Commented Oct 23, 2012 at 20:16
  • yes only towo digits ,the input is decimal Commented Oct 23, 2012 at 20:18
  • 6
    The C# development team should be embarrassed (and take action) that this very common operation has no single Math.function such as Math.DecimalPart(double x) or something. There is way too much "did you try this, did you think about that" for something many of us need to do often.
    – philologon
    Commented Jan 15, 2018 at 15:44

18 Answers 18

248

the best of the best way is:

var floatNumber = 12.5523;

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

result you can convert however you like

6
  • 15
    This should be the accepted answer, a Math solution to a Math question, without all that tedious mucking about in string manipulation
    – johnc
    Commented Oct 1, 2014 at 4:57
  • 27
    I think this solution have a "problem". If the floatNumber was "10.2", the variable x will be something like "0.19999999999999929". Even if this works as expected, the result would be "0.2" and not "2".
    – Dherik
    Commented Nov 25, 2014 at 15:20
  • 4
    @Dherik Float and Double values always have small errors under subtraction in the last few decimal places. You should not be considering those as significant. If you actually need that kind of precision, you should be using Decimal type. If you can't switch to Decimal (or just don't want to), then you ought to keep track of the expected precision somehow and account for that in comparison operations. I usually use 4 decimal places, but there may be exceptions to that.
    – philologon
    Commented Jan 5, 2015 at 2:43
  • 1
    From msdn.microsoft.com/en-us/library/… : "Because some numbers cannot be represented exactly as fractional binary values, floating-point numbers can only approximate real numbers"
    – philologon
    Commented Jan 5, 2015 at 2:43
  • 1
    Final comment: Using Math.Truncate was the intent of the author's of the Math library for this kind of situation. @Matterai 's answer should be the accepted one.
    – philologon
    Commented Jan 5, 2015 at 2:49
88
var decPlaces = (int)(((decimal)number % 1) * 100);

This presumes your number only has two decimal places.

2
  • 1
    (318.40d % 1) * 100 outputs 39.9999999999977, you can use casting to get around the rounding error: var decPlaces = (int)(((decimal)number % 1) * 100);
    – orad
    Commented Jul 13, 2015 at 18:03
  • @orad Good call there - floating point numbers always have these little inaccuracies, so casting it is pretty prudent to ensure consistent behavior. I'll update my answer, though Matterai's is still more technically correct.
    – tmesser
    Commented Jul 14, 2015 at 5:21
69

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

double frac = value % 1;
1
  • 14
    a note: for negative values, it is negative: -12.34 % 1 => -0.33999999999999986
    – Alex Poca
    Commented Apr 4, 2019 at 14:09
19

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.

2
  • 1
    Thumbs up for mod ones Commented Aug 26, 2016 at 14:13
  • I used this...10.2d.ToString("0.00", CultureInfo.InvariantCulture).Split('.')[1]
    – Ziggler
    Commented May 7, 2018 at 21:28
11

Better Way -

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

Output -

56
2
  • 2
    Did not test, but this suffers from float inaccuracy, no?
    – mafu
    Commented May 2, 2015 at 13:03
  • For 10.20 it will output 19. See my answer.
    – orad
    Commented Jul 13, 2015 at 18:44
9

The simplest variant is possibly with Math.truncate()

double value = 1.761
double decPart = value - Math.truncate(value)
1
  • does not work for value below zero like 0.25
    – HelloWorld
    Commented Apr 5, 2022 at 15:04
6

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))
1
  • For the super lazy: double fract(double x) { return x - System.Math.Floor(x); } Commented Jun 25, 2020 at 21:02
1
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.

1
  • This is a, uuh, "not very good" approach. It allocates strings, arrays, and performs string operations. All of this is unnecessary, as we can see from the other answers.
    – Simon
    Commented Jun 9 at 17:58
1
int last2digits = num - (int) ((double) (num /  100) * 100);
1
  • Question is to get first 2 decimal digits. For number 318.401567d your solution outputs 0.401567 where 40 is expected.
    – orad
    Commented Jul 13, 2015 at 18:27
0

In my tests this was 3-4 times slower than the Math.Truncate answer, but only one function call. Perhaps someone likes it:

var float_number = 12.345;
var x = Math.IEEERemainder(float_number , 1)
-1
    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;
    }
-1
 string input = "0.55";
    var regex1 = new System.Text.RegularExpressions.Regex("(?<=[\\.])[0-9]+");
    if (regex1.IsMatch(input))
    {
        string dp= regex1.Match(input ).Value;
    }
1
  • 2
    It would be awesome if you could add a description on how the regex helps solving the problem
    – Cleptus
    Commented Nov 9, 2020 at 13:42
-1
var d = 1.5;
var decimalPart = Convert.ToInt32(d.ToString().Split('.')[1]);

it gives you 5 from 1.5 :)

6
  • This will give you 25 for 0.25 though
    – mousetail
    Commented Oct 26, 2021 at 7:42
  • @mousetail as the question wants :)
    – Inside Man
    Commented Oct 26, 2021 at 7:58
  • No, he wants 50 for 0.5
    – mousetail
    Commented Oct 26, 2021 at 8:02
  • @mousetail no, he wants 50 from 2.50
    – Inside Man
    Commented Oct 26, 2021 at 8:27
  • There is no difference between 2.5 and 2.50
    – mousetail
    Commented Oct 26, 2021 at 8:28
-1

My answer is based on a suspected use-case behind this question and people coming to this question.

The following example program will display a decimal value in a way that appears like a currency like 34.99 or 1.00 unless it has further precision, in which case it will display the whole precision like, 290.19882 or 128.00001

Please critique. Remember the design is for display.

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine(ConvertToString(5.00m));
        Console.WriteLine(ConvertToString(5.01m));
        Console.WriteLine(ConvertToString(5.99m));
        Console.WriteLine(ConvertToString(5.000000191m));
        Console.WriteLine(ConvertToString(5.000000191000m));
        Console.WriteLine(ConvertToString(51028931298373.000000191000m));
    }

    public static string ConvertToString(decimal value)
    {
        decimal whole = Math.Truncate(value);
        decimal fractional = value - whole;
        return ConvertToString(whole, fractional);
    }

    public static string ConvertToString(decimal whole, decimal fractional)
    {
        if (fractional == 0m)
        {
            return $"{whole:F0}.00";
        }
        else
        {
            string fs = fractional.ToString("F28").Substring(2).TrimEnd('0');
            return $"{whole:F0}.{fs}";
        }
    }
}

Results

5.00
5.01
5.99
5.000000191
5.000000191
51028931298373.000000191
-2

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

1
  • Not very popular with Regex.Match but I've received the following error when trying to get the value of the decimal ArgumentException was unhandled: parsing "\.(?\d+)" - Unrecognized grouping construct. Commented Oct 23, 2012 at 20:45
-2

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
-2

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 .

2
  • This will work: Int32.Parse((12.05123d.ToString("0.00").Split('.')[1]))
    – orad
    Commented Jul 13, 2015 at 19:49
  • 2
    Because you are casting it to a string to do string manipulation. I don't think you realize just how slow and wasteful this is.
    – dmarra
    Commented Feb 18, 2016 at 19:02
-3

It is very simple

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

       Debug.Log(decimalPart);
1
  • Mathf.PingPong does not exist in plain C#
    – Simon
    Commented Jun 9 at 17:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.