Get decimals of a double?
c#
Solution
If you take the remainder of the object divided by `1` you'll get the fractional portion of that number:
double remainder = someDouble % 1;
To write the whole method out, it's as simple as:
public double Calculate(double x, double add)
{
return Math.Floor(x) + (x + add) % 1;
}
(This is one of those times where you're glad that `%` computes the remainder, rather than the modulus. This will work as is for negative numbers as well.)
Problem
I have a function that adds a double to another double but I need to add only to the digits after the decimal point and the number of digits varies based on the size of the number. ``` public double Calculate(double x, double add) { string xstr; if (x >= 10) xstr = x.ToString("00.0000", NumberFormatInfo.InvariantInfo); if (x >= 100) xstr = x.ToString("000.000", NumberFormatInfo.InvariantInfo); if (x < 10) xstr = x.ToString("0.00000", NumberFormatInfo.InvariantInfo); string decimals = xstr.Remove(0, xstr.IndexOf(".") + 1); decimals = (Convert.ToDouble(decimals) + add).ToString(); xstr = xstr.Substring(0, xstr.IndexOf(".") + 1) + decimals; x = Convert.ToDouble(xstr, NumberFormatInfo.InvariantInfo); return x; } ``` I'm wondering if there isn't a simpler way to do this without having to convert the number to string first and then adding to the decimal part of it. As you can see the number to be added to should always be a 6 digit number where ever the decimal separator is.