What is the equivelant of the Excel function ROUNDDOWN(number, num_digits) in C#?
As the title suggests I开发者_Python百科 need a C# equivelant of ROUNDDOWN.
For example, if you take the figure 13.608000, the output i am looking for is 13.60.
I can't seem to find anything that covers exactly what I am after.
Here's a direct port of the Excel function for variable number of decimal places
public double RoundDown(double number, int decimalPlaces)
{
return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
}
e.g. RoundDown (13.608000,2) = 13.60, RoundDown(12345,-3) = 12000,
You could do the following:
var rounded = Math.Floor(13.608000 * 100) / 100;
Note that Math.Floor() rounds down to the nearest integer, hence the need to multiply, round down, and then divide.
Here's the right solution:
double RoundDown(double value, int digits)
{
if (value >= 0)
return Math.Floor(value * Math.Pow(10, digits)) / Math.Pow(10, digits);
return Math.Ceiling(value * Math.Pow(10, digits)) / Math.Pow(10, digits);
}
RichardW1001's answer is almost right, he just didn't account for the rounding of negative values.
For rounding down, use Math.Floor. To round off to a different factor than 1.0, multiply before calling Floor and divide afterwards.
double x = 0.01 * Math.Floor(100 * y);
Math.Round function should do it, http://msdn.microsoft.com/en-us/library/zy06z30k.aspx
Workaround:
decimal x = 13.6080001;
int places = 2;
int result = (int)(Math.Round(x - (0.5 * Math.Pow(10, 0 - places), places)));
精彩评论