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
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;
}
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))
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);
}
}
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
int last2digits = num - (int) ((double) (num / 100) * 100);