I have a double value: 0.314285 which I want to Round off to 5 decimal places. From a mathematical point of view my expectant result is: 0.31429. In my code I use the Math.Round with MidPointRounding.AwayFromZero parameter overload, the resultant output being: 0.31428.
Is there another way to implement to have the output result as: 0.31429??
You should read the rounding and precision article. The real representation of your number in memory can be something like 0.3142849999999999, and therefore you are getting 0.31428 result. Using a decimal type can help to solve this issue
var value = 0.314285m;
var result = Math.Round(value, 5, MidpointRounding.AwayFromZero); //0.31429
public static double RoundUp(double i, int decimalPlaces)
{
var power = Math.Pow(10, decimalPlaces);
return Math.Ceiling(i * power) / power;
}
RoundDown(0.314285, 5); //0.31429
Math.Round(decimal number to round, int number of decimal places)
I think this should work for what you are trying to do.
Related
here is what I'm trying to do:
double result = Math.Pow((1 + 8), 60) - 1;
And the result variable is:
1.7970102999144311E+57 double
And trying to:
Math.Round(result, 5);
Returns same : 1.7970102999144311E+57 double
I'd like to round it to 1.79701 for example
Any solutions ?
You're misunderstanding what you're seeing.
1.7970102999144311E+57
Is scientific notation for
1797010299914431100000... (with 41 trailing zeros).
It is a whole number, thus rounding it to 5 decimal places will correctly return the same value.
What you want to do is format the output of the number
String.Format(CultureInfo.InvariantCulture, "{0:0.#####E+0}", result);
Which returns 1.79701E+57. Note that this is a very different number from 1.79701
The problem you're having is that Math.Round rounds things to the right of the decimal point. For example if you're dealing with currency and you perform an operation that leaves you with $1.5234524, you would use:
Math.Round(1.5234524,2);
// output 1.52
The number you're dealing with is actually scientific notation for a very large number with nothing to the right of the decimal point. This is why the result of Math.Round is the same as the input.
The earlier comments and answers are correct. But to get what you are trying to achieve you can use the following:
double result = Math.Pow((1 + 8), 60) - 1;
string s = String.Format("{0:E5}", result);
double d = Double.Parse(s);
My scenario is that if
47/15= 3.13333
i want to convert it into 4, if the result has decimal i want to increase the result by 1, right now i am doing this like
float res = ((float)(62-15) / 15);
if (res.ToString().Contains("."))
{
string digit=res.ToString().Substring(0, res.ToString().IndexOf('.'));
int incrementDigit=Convert.ToInt16(k) + 1;
}
I want to know is there any shortcut way or built in function in c# so that i can do this fast without implementing string functions.
Thanks a lot.
Do you mean you want to perform integer division, but always rounding up? I suspect you want:
public static int DivideByFifteenRoundingUp(int value) {
return (value + 14) / 15;
}
This avoids using floating point arithmetic at all - it just allows any value which isn't an exact multiple of 15 to be rounded up, due to the way that integer arithmetic truncates towards zero.
Note that this does not work for negative input - for example, if you passed in -15 this would return 0. you could fix this with:
public static int DivideByFifteenRoundingUp(int value) {
return value < 0 ? value / 15 : (value + 14) / 15;
}
Use Math.Ceiling Quoting MSDN:
Returns the smallest integral value that is greater than or equal to
the specified decimal number.
You are looking for Math.Ceiling().
Convert the value you have to a Decimal or Double and the result of that method is what you need. Like:
double number = ((double)(62-15) / (double)15);
double result = Math.Ceiling(number);
Note the fact that I cast 15 to a double, so I avoid integer division. That is most likely not what you want here.
Another way of doing what you ask is to add 0.5 to every number, then floor it (truncate the decimal places). I'm afraid I don't have access to a C# compiler right now to confirm the exact function calls!
NB: But as others have confirmed, I would think the Math.Ceiling function best communicates to others what you intend.
Something like:
float res = ((float)(62-15) / 15);
int incrementDigit = (int)Math.Ceiling(res);
or
int incrementDigit = (int)(res + 0.5f);
I am calculating the average of some values. Everything works fine.
What I want to do is to round the double to the 2nd decimal place.
e.g.
I would have 0.833333333333333333 displayed as
0.83
Is there anyway to do this?
Round the double itself like:
Math.Round(0.83333, 2, MidpointRounding.AwayFromZero);
(You should define MidpointRounding.AwayAwayFromZero to get the correct results. Default this function uses bankers rounding. read more about bankers rounding: http://www.xbeat.net/vbspeed/i_BankersRounding.htm so you can see why this won't give you the right results)
Or just the display value for two decimals:
myDouble.ToString("F");
Or for any decimals determined by the number of #
myDouble.ToString("#.##")
You say displays as - so that would be:
var d = value.ToString("f2");
See Standard numeric format strings
If you actually want to adjust the value down to 2dp then you can do what #middelpat has suggested.
Use
Math.Round(decimal d,int decimals);
as
Math.Round(0.833333333,2);
This will give you the result 0.83.
double d = 0.833333333333333333;
Math.Round(d, 2).ToString();
Try
decimalVar = 0.833333333333333333;
decimalVar.ToString ("#.##");
If you want to see 0.85781.. as 0.85, the easiest way is to multiply by 100, cast to int and divide by 100.
int val = (int)(0.833333333333333333 * 100);
var result = val /100;
It should produce the result you're looking for.
I have a decimal number which can be like the following:
189.182
I want to round this up to 2 decimal places, so the output would be the following:
189.19
Is there built in functionality for this in the Math class, or something else? I know the ceiling function exists but this doesn't seem to do what I want - it'll round to the nearest int, so just '189' in this case.
Multiply by 100, call ceiling, divide by 100 does what I think you are asking for
public static double RoundUp(double input, int places)
{
double multiplier = Math.Pow(10, Convert.ToDouble(places));
return Math.Ceiling(input * multiplier) / multiplier;
}
Usage would look like:
RoundUp(189.182, 2);
This works by shifting the decimal point right 2 places (so it is to the right of the last 8) then performing the ceiling operation, then shifting the decimal point back to its original position.
You can use:
decimal n = 189.182M;
n = System.Math.Ceiling (n * 100) / 100;
An explanation of the various rounding functions can be found here.
Be aware that formulae like this are still constrained by the limited precision of the double type, should that be the type you are using (your question stated decimal but it's possible you may just have meant a floating point value with fractional component rather than that specific type).
For example:
double n = 283.79;
n = System.Math.Ceiling (n * 100);
will actually give you 28380, not the 283.79 you would expect(a).
If you want accuarate results across the board, you should definitely be using the decimal type.
(a) This is because the most accurate IEEE754 double precision representation of 283.79 is actually:
283.790000000000020463630789891
That extra (admittedly minuscule) fractional component beyond the .79 gets ceilinged up, meaning it will give you a value higher than you would expect.
var numberToBeRound1 = 4.125;
var numberToBeRound2 = 4.175;
var numberToBeRound3 = 4.631;
var numberToBeRound4 = 4.638;
var numberOfDecimalPlaces = 2;
var multiplier = Math.Pow(10, numberOfDecimalPlaces);
//To Round Up => 4.13
var roundedUpNumber = Math.Ceiling(numberToBeRound1 * multiplier) / multiplier;
//To Round Down => 4.12
var roundedDownNumber = Math.Floor(numberToBeRound1 * multiplier) / multiplier;
//To Round To Even => 4.12
var roundedDownToEvenNumber = Math.Round(numberToBeRound1, numberOfDecimalPlaces, MidpointRounding.ToEven);
//To Round To Even => 4.18
var roundedUpToEvenNumber = Math.Round(numberToBeRound2, numberOfDecimalPlaces, MidpointRounding.ToEven);
//To Round To Away From Zero => 4.63
var roundedDownToAwayFromZero = Math.Round(numberToBeRound3, numberOfDecimalPlaces, MidpointRounding.AwayFromZero);
//To Round To Away From Zero => 4.64
var roundedUpToAwayFromZero2 = Math.Round(numberToBeRound4, numberOfDecimalPlaces, MidpointRounding.AwayFromZero);
How about
0.01 * ceil(100 * 189.182)
In .NET Core 3.0 and later versions, three additional rounding strategies are available through the MidpointRounding enumeration.
Besides MidpointRounding.AwayFromZero and MidpointRounding.ToEven it now includes:
1. MidpointRounding.ToNegativeInfinity
2. MidpointRounding.ToPositiveInfinity
3. MidpointRounding.ToZero
For this specific question you need to use MidpointRounding.ToPositiveInfinity, this will round the number up always.
Note this only works if the number isn't negative. See table below for examples.
Original number
ToNegativeInfinity
ToPositiveInfinity
ToZero
3.55
3.5
3.6
3.5
2.83
2.8
2.9
2.8
2.54
2.5
2.6
2.5
2.16
2.1
2.2
2.1
-2.16
-2.2
-2.1
-2.1
-2.54
-2.6
-2.5
-2.5
-2.83
-2.9
-2.8
-2.8
-3.55
-3.6
-3.5
-3.5
For more information about midpointrounding see https://learn.microsoft.com/en-us/dotnet/api/system.midpointrounding
And of course the code to make it work:
// function explained: Math.Round(number, amount of decimals, MidpointRounding);
decimal number = 189.182m;
number = Math.Round(number, 2, MidpointRounding.ToPositiveInfinity);
// result: number = 189.19
public static decimal RoundUp(decimal input, int places)
{
decimal multiplier = (decimal)Math.Pow(10, places);
return decimal.Ceiling(input * multiplier) / multiplier;
}
// Double will return the wrong value for some cases. eg: 160.80
public static decimal RoundUp(decimal input, int places)
{
decimal multiplier = Convert.ToDecimal(Math.Pow(10, Convert.ToDouble(places)));
return Math.Ceiling(input * multiplier) / multiplier;
}
One other quirky but fun way to do it is Math.Round() after offsetting the number.
decimal RoundUp(decimal n, int decimals)
{
n += decimal.Parse($"1e-{decimals}", System.Globalization.NumberStyles.AllowExponent) / 2;
n -= 1e-28m;
return Math.Round(n, decimals);
}
decimal RoundDown(decimal n, int decimals)
{
n -= decimal.Parse($"1e-{decimals}", System.Globalization.NumberStyles.AllowExponent) / 2;
n += 1e-28m;
return Math.Round(n, decimals);
}
Is has the advantage of not using Math.Pow() which uses double and thus can cause unpredictable rounding errors.
This solution basically uses the fact that midpoint rounding can be turned into up/down rounding if you increase/decrease the number a little:
Math.Round(3.04m, 1) is 3.0 - not what we want
Let's add 0.04(9) to it
Math.Round(3.0899999999999999999999999999m, 1) is 3.1 - success!
Subtracting 1e-28m (= 0.0000000000000000000000000001) is important, because we want to be able to round up 3.0000000000000000000000000001 to 4, but 3.0000000000000000000000000000 should stay 3.
Using C#, I want to format a decimal to only display two decimal places and then I will take that decimal and subtract it to another decimal. I would like to be able to do this without having to turn it into a string first to format and then convert it back to a decimal. I'm sorry I forget to specify this but I don't want to round, I just want to chop off the last decimal point. Is there a way to do this?
If you don't want to round the decimal, you can use Decimal.Truncate. Unfortunately, it can only truncate ALL of the decimals. To solve this, you could multiply by 100, truncate and divide by 100, like this:
decimal d = ...;
d = Decimal.Truncate(d * 100) / 100;
And you could create an extension method if you are doing it enough times
public static class DecimalExtensions
{
public static decimal TruncateDecimal(this decimal #this, int places)
{
int multipler = (int)Math.Pow(10, places);
return Decimal.Truncate(#this * multipler) / multipler;
}
}
You can use: Math.Round(number,2); to round a number to two decimal places.
See this specific overload of Math.Round for examples.
Math.Round Method (Decimal, Int32)
You don't want to format it then, but to round it. Try the Math.Round function.
Take a look at Math.Round