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
18 Answers
the best of the best way is:
var floatNumber = 12.5523;
var x = floatNumber - Math.Truncate(floatNumber);
result you can convert however you like
-
15This should be the accepted answer, a Math solution to a Math question, without all that tedious mucking about in string manipulation– johncCommented Oct 1, 2014 at 4:57
-
27I 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".– DherikCommented 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. Commented Jan 5, 2015 at 2:43
-
1From 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" Commented Jan 5, 2015 at 2:43
-
1Final 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. Commented Jan 5, 2015 at 2:49
var decPlaces = (int)(((decimal)number % 1) * 100);
This presumes your number only has two decimal places.
-
1
(318.40d % 1) * 100
outputs39.9999999999977
, you can use casting to get around the rounding error:var decPlaces = (int)(((decimal)number % 1) * 100);
– oradCommented 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.– tmesserCommented Jul 14, 2015 at 5:21
There is a cleaner and ways faster solution than the 'Math.Truncate' approach:
double frac = value % 1;
-
14a note: for negative values, it is negative: -12.34 % 1 => -0.33999999999999986 Commented Apr 4, 2019 at 14:09
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 of39
) - for
47.612345
outputs:61
(instead of612345
) - for
3.01
outputs:01
(instead of1
)
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.
-
1
-
I used this...10.2d.ToString("0.00", CultureInfo.InvariantCulture).Split('.')[1]– ZigglerCommented May 7, 2018 at 21:28
Better Way -
double value = 10.567;
int result = (int)((value - (int)value) * 100);
Console.WriteLine(result);
Output -
56
-
2
-
The simplest variant is possibly with Math.truncate()
double value = 1.761
double decPart = value - Math.truncate(value)
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))
-
For the super lazy:
double fract(double x) { return x - System.Math.Floor(x); }
Commented Jun 25, 2020 at 21:02
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.
-
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.– SimonCommented Jun 9 at 17:58
int last2digits = num - (int) ((double) (num / 100) * 100);
-
Question is to get first 2 decimal digits. For number
318.401567d
your solution outputs0.401567
where40
is expected.– oradCommented Jul 13, 2015 at 18:27
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)
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;
}
string input = "0.55";
var regex1 = new System.Text.RegularExpressions.Regex("(?<=[\\.])[0-9]+");
if (regex1.IsMatch(input))
{
string dp= regex1.Match(input ).Value;
}
-
2It would be awesome if you could add a description on how the regex helps solving the problem– CleptusCommented Nov 9, 2020 at 13:42
var d = 1.5;
var decimalPart = Convert.ToInt32(d.ToString().Split('.')[1]);
it gives you 5
from 1.5
:)
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
Use a regex: Regex.Match("\.(?\d+)")
Someone correct me if I'm wrong here
-
Not very popular with
Regex.Match
but I've received the following error when trying to get the value of the decimalArgumentException was unhandled: parsing "\.(?\d+)" - Unrecognized grouping construct.
Commented Oct 23, 2012 at 20:45
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
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 .
It is very simple
float moveWater = Mathf.PingPong(theTime * speed, 100) * .015f;
int m = (int)(moveWater);
float decimalPart= moveWater -m ;
Debug.Log(decimalPart);
decimal
,float
,string
, ...?