I'm stuck with a little issue here, say you have the following code:
int whole = 0;
double decimal = 88.00
whole = decimal / 1.5; //now the answer is 58.66
So here's the issue, explicitly casting a double to an int is easy enough. But if I do this now 'whole' is going to be set to 59. This - is not so good, I want it to be set to the last whole number (being 58).
How do you do this in C#?
To round doubles to integers, you have 4 basic math functions:
Math.Round() - Rounds to the nearest whole number (or user specified number of deciml places), and lets you choose to round middle points up or down.
Math.Floor() - Rounds to the first whole number toward negative infinity.
Math.Ceiling() - Rounds to the first whole number toward positive infinity.
Math.Truncate() - Rounds to the first whole number toward zero.
I think you want either Floor or Truncate. Both round down for positive numbers, but Truncate rounds -3.6 to -3, while Floor rounds it to -4.
Casting to int does the same as truncating, so you can use that if you prefer.
Math.Floor:
whole = (int)Math.Floor(decimal / 1.5);
If you cast double to int, the answer will NOT be 59 -- it will be 58. When casting double to int, the value will be rounded towards zero. So, this is sufficient:
int whole = 0;
double x = 88.00;
whole = (int)(x / 1.5); // whole will be 58
Use Math.Floor if you want to round to the last whole number, and Math.Ceiling if you want to round to the next.
If you need rounding, it's pretty common to use:
whole = (int)(decimal / 1.5 + 0.5);
Without the 0.5, you're truncating, not rounding.
If you have a rounding function in your math libraries, that's good too. Some of these will do the odd/even thing for rounding 0.5 to avoid a little bit of data skew.
This will convert the double value into int:
whole = (int)(decimal / 1.5);
Also, you can use Math.Floor(doubleValue).
Related
I have a problem to round a number to two decimal places.
I have the number 3106.4647771976413339683766317M.
The correct round to two decimal places is 3106.47, but using Math.Round(value, 2, MidpointRounding.AwayFromZero) the number is 3106.46.
The problem is the method look to third decimal place to round, but if it look to fourth decimal place will generate the correct number.
Someone has something like that?
Mathematically, the correct round to two decimal places is 3106.46.
What you probably want is a ceiling:
Math.Ceiling(3106.4647771976413339683766317M * 100) / 100
produces 3106.47. There is no version of Math.Ceiling accepting a number of decimal places, that's why there are multiplication and division.
In addition, note that there is a caveat in this expression:
Math.Round(value, 2, MidpointRounding.AwayFromZero)
Math.Round does not have a variant with three arguments, where the first one is a decimal. It works, because the value is implicitly converted to double. However, this is unwanted.
If you really want to round that way (more of a common mistake than actual rounding in the traditional sense) you can round up from the furthest right digit and move left one place at a time.
double numberToRound = 3106.4647771976413339683766317;
int placesToRoundTo = 2;
int smallestPlaceIndex = 24; // you would need to determine this value
for (int i = smallestPlaceIndex; i >= placesToRoundTo)
{
numberToRound = Math.Round(numberToRound, i, MidpointRounding.AwayFromZero);
}
There isn't a simple built-in method to do this because it isn't normal rounding.
I'm testing a system which gave 10% of discount in a product, this means 102.555 of discount, but the system only use 2 fractional digits, so it gave 102.55.
The problem is if I execute this:
Math.Round(102.555, 2, MidpointRounding.AwayFromZero)
The output is: 102.56
And if I execute this:
Math.Round(102.555, 2, MidpointRounding.ToEven)
The output is also 102.56.
I was using Math.Round method with all scenarios, until this came up.
What am I doing wrong?
Why is 102.555 returning 102.56 with MidpointRounding.AwayFromZero?
How Can I do something to return 102.55 from 102.555?
Why is 102.555 returning 102.556 with MidpointRounding.AwayFromZero?
I presume "102.556" should read "102.56" here.
Because MidpointRounding indicates what happens when you are rounding a number where the significant digit for rounding (i.e. the last disappearing digit) at radix 10 is 5. This is the case for your number 102.555, so when rounding to two decimal places, there are two options:
102.55
102.56
MidpointRounding.AwayFromZero picks the option that is further away from zero - in this case (as these are positive numbers) the greater one, namely 102.56.
Ok, I found the answer:
https://stackoverflow.com/a/13483693/375422
public double TruncateDown(double number, int decimalPlaces)
{
return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
}
public double TruncateUp(double number, int decimalPlaces)
{
return Math.Ceiling(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
}
In my case, I want to round down.
While string truncation will work, you want the floor() function used this way:
double value = Math.Floor(Math.Int(sourceVal * 100)) / 100;
There are two types of rounding, the banker's rounding (i.e. to even), and everyday rounding (i.e. away from zero).
Simply put, away from zero rounding simply checks the number before the precision specified, and if it is 5 or greater, then it rounds up.
However, to even checks whether it will approach an even number when it rounds up, and if so, then it rounds up. However, it it approaches an odd number, then it won't round up.
Bear in mind, the default method Math.Round(x, y) uses to even implicitly.
To even gives a complimentary correct calculation. See here. 1.5 + 2.5 = 4. If you round each one and sum them up, you will still get 4, however, you will get calculation error if you do the same with away from zero.
var x = Math.Round(1.5, 0) + Math.Round(2.5, 0); // 4
var y = Math.Round(1.5, 0, MidpointRounding.AwayFromZero) + Math.Round(2.5, 0, MidpointRounding.AwayFromZero); // 5!
See here for more info: https://msdn.microsoft.com/en-us/library/system.midpointrounding(v=vs.110).aspx
Edit 1:
Following O. R. Mapper & sgmoore comments, I just realized that the point of bankers rounding is to have the odds of rounding up or down almost equally the same over the course of random numbers.
In away from zero rounding, you end up with 1-4 (four odds) rounding down, and 5-9 rounding up (5 odds).
However, in bankers rounding, 1-4 (four odds) will round down, and 6-9 will round up (4 odds), and then we have 5 that will either round up or down, and when applied to random numbers, the odds of rounding up is almost like the odds of rounding down. And that gives a better chance for more accurate calculation specially when summing up.
You can find out more here: Why does .NET use banker's rounding as default?
Edit 2:
If you want to truncate, you can simply use:
decimal x = 102.555M;
decimal truncated = Math.Truncate(x * 100) / 100; // 102.55;
There is a great system to round to the nearest integer adding half to the number.
For example if you want to round 3.8 to 4, you first add 0.5 (it will bring it to 4.3) and then cut the 0 (using mod or int).
In your sample, you need to add 0.005 and then cut the last digit.
It can be done with toFixed(2) to keep two digits after the dot.
Here you have some console output...
(102.555+.005).toFixed(2)
"102.56"
(102.555).toFixed(2)
"102.56"
toFixed rounds to the nearest number so in this case you don't need to add half but to substract it.
(102.555-.005).toFixed(2)
"102.55"
Why does below code returns 1299.49 ? According to msdn documentation it should give 1299.5.
Console.WriteLine(Math.Round( 1299.492, 2, MidpointRounding.AwayFromZero))
You are rounding to 2 decimal places, hence why 1299.49 is returned.
If you want it to be 1299.5, round to 1 decimal place.
Console.WriteLine(Math.Round( 1299.492, 1, MidpointRounding.AwayFromZero))
From the documentation about AwayFromZero:
When a number is halfway between two others, it is rounded toward the nearest number that is away from zero.
https://msdn.microsoft.com/en-us/library/system.midpointrounding(v=vs.110).aspx
You may be confused as to how this overload works. According to MSDN on MidpointRounding:
When a number is halfway between two others, it is rounded toward the nearest number that is away from zero.
In your case, 1299.492 is not halfway between 1229.49 and 1299.50, so MidpointRounding.AwayFromZero doesn't even apply.
It looks like what you're actually trying to do is round up to the nearest 2 decimal places. In that case, you want something like this answer:
public static double RoundUp(double input, int places)
{
double multiplier = Math.Pow(10, Convert.ToDouble(places));
return Math.Ceiling(input * multiplier) / multiplier;
}
This rounds up to the specified decimal places by multiplying by 10^places (100 if you need 2 places), calling Math.Ceiling, and then dividing.
This works:
Console.WriteLine(RoundUp(1299.492, 2)); // 1299.5
I'm trying to convert Single to Double while maintaining the original value. I've found the following method:
Single f = 5.2F;
Double d1 = f; // 5.19999980926514
Double d2 = Double.Parse(f.ToString()); // 5.2 (correct)
Is this practice recommendable? I don't need an optimal method, but the intended value must be passed on to the double. Are there even consequences to storing a rounded value in a double?
You could use "decimal" instead of a string.
float f = 5.2F;
decimal dec = new decimal(f);//5.2
double d = (double)dec; //5.2
The conversion is exact. All the Single values can be represented by a Double value, because they are "built" in the same way, just with more possible digits. What you see as 5.2F is in truth 5.1999998092651368. If you go http://www.h-schmidt.net/FloatConverter/IEEE754.html and insert 5.2 you'll see that it has an exponent of 2^2 (so 4) and a mantissa of 1.2999999523162842. Now, if you multiply the two numbers you'll get 5.1999998092651368.
Single have a maximum precision of 7 digits, so .NET only shows 7 digits. With a little rounding 5.1999998092651368 is 5.2
If you know that your numbers are multiples of e.g. 0.01, I would suggest that you convert to double, round to the nearest integer, and subtract that to get the fractional residue. Multiply that by 100, round to the nearest integer, and then divide by 100. Add that to the whole-number part to get the nearest double representation to the multiple of 0.01 which is nearest the original number.
Note that depending upon where the float values originally came from, such treatment may or may not improve accuracy. The closest float value to 9000.02 is about 9000.019531, and the closest float value to 9000.021 is about 9000.021484f. If the values were arrived at by converting 9000.020 and 9000.021 to float, the difference between them should be about 0.01. If, however, they were arrived at by e.g. computing 9000f+0.019531f and 9000f+0.021484f, then the difference between them should be closer to 0.02. Rounding to the nearest 0.01 before the subtract would improve accuracy in the former case and degrade it in the latter.
Here's my formula:
int a;
int b;
int c;
double multiplier;
amount = Convert.ToInt32(Math.Round(multiplier * a * (4 * b + c) / 100, 0));
When I get a value that would make it have a decimal of .5 or greater it's rounding down instead. How do I make it so that this equation will round off the final result (and I know how to display as a string)?
The default rounding behvaior for Math.Round is ToEven, which rounds numbers on the midpoint to the nearest even integer. it does not always round down, as you are claiming, it rounds down exactly half of the time, and round up exactly half of the time. If you wish the midpoint to always round away from zero then you need to specify MidpointRounding.AwayFromZero to Math.Round.
(In addition to the problem Servey pointed out...)
Be mindful of the mode for some rounding methods. In some cases, you need to use the "AwayFromZero" mode in order for decimals .5 and greater to round up, and less than .5 to round down.
See the documentation. The "Math.Round(Decimal, MidpointRounding) example" shows what I mean.