Reputation:
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.
Upvotes: 5
Views: 181
Reputation: 6374
Here is yet another version:
public double Calculate(double x, double add)
{
return (x - (int)x) + (add - (int)add);
}
Upvotes: 0
Reputation: 203802
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.)
Upvotes: 8
Reputation: 484
A little more elegant and much more faster:
public static double Calculate(double x, double add)
{
var pow = 5 - Math.Truncate(Math.Log10(x));
var multiplier = Math.Pow(10, pow);
var decimals = Math.Truncate((x % 1)* multiplier) + add;
x = Math.Truncate(x) + Math.Truncate(decimals) / multiplier;
return x;
}
Upvotes: 1
Reputation: 701
So all you want to do is add the fractional part of each value? Why don't you just do this?
public double Calculate(double x, double y)
{
double fractional_x = x - Math.Floor(x);
double fractional_y = y - Math.Floor(y);
return fractional_x + fractional_y;
}
Upvotes: 0