how to make the Rounded number ?
Example : 3341.48 to 3342.00
It seems you always want to round up here. In that case use
Math.Ceiling(3341.48)
This will return 3342.
If you want to round towards the nearest whole number, use
Math.Round(3341.48)
This will return 3341. Note that Bankers roundingis the default setting here, that might cause some unexpected result for rounding X.50.
If you want 3341.48 to round up to 3342, it sounds like you might want Math.Ceiling:
decimal m = 3341.48m;
decimal roundedUp = Math.Ceiling(m);
This will always round up - so 3341.0000001 would still round to 3342, for example. If that's not what you're after, please specify the circumstances in which you want it to round up, and those in which you want it to round down instead.
Note that this will round up to 3342, not 3342.00 - it doesn't preserve the original precision, because you've asked for an integer value by using Math.Ceiling.
It's relatively unusual to then want to force the precision to 2, but you could divide by 100 and then multiply by 100 again, if necessary. Alternatively, if you only need this for output you should look into formatting the result appropriately rather than changing the value.
Use Math.Round(number) if you want to round number to the nearest integer.
Use Math.Round(number,digits) if you want to round number to a specified number of fractional digits.
If you want to round to lower/higer value use Math.Floor(number) / Math.Ceiling(number) instead.
To round monetary amounts to 5 cents:
amount = 20 * int(amount / 20)
Related
Although my question sounds trivial, it really is NOT. Hope you can help me.
I want to implement interval arithmetic in my .NET (C#) project. This means that every number is defined by an lower bound and an upper bound. This is helpfull for problems like
1 / 3 = 0.333333333333333 (15 significant digits)
since you would then have
1 / 3 = [ 0.33333333333333 , 0.333333333333334 ] (14 significant digits each)
, so I now FOR SURE that the right answer lays between those two numbers. Without the interval representation I would already have a rounding error with me (i.e. 0.0000000000000003).
To achieve this I wrote my own Interval type that overloads all standard operators like +-*/, etc. To make this type work correctly I need to be able to round the result of 1 / 3 in two directions. Rounding the result down will give me the lower bound for my interval, rounding the result up will give me the upper bound for my interval.
.NET has the Math.Round(double,int) method which rounds the double to int decimal places. Looks great but it can't be forced to round up/down. Math.Round(1.0/3.0,14) would round down, but the also needed up-rounding to 0.33...34 can't be achieved like this.
But there are Math.Ceil and Math.Floor you might say! Okay, those methods round to the next lower or upper integer. So if I want to round to 14 decimal places I first need to reform my result:
1 / 3 = 0.333333333333333 -> *E14 -> 33333333333333.3
So now I can call Math.Ceil and Math.Floor and get both rounded results after reforming back
33333333333333 & 33333333333334 -> /E14 -> 0.33333333333333 & 0.33333333333334
Looks great, but: Let's say my number goes near the double.MaxValue. I can't just *E14 a value near double.MaxValue since this will give me an OverflowException. So this is no solution either.
And, to top all of these facts: All this fails even harder when trying to round 0.9999999999999999999999999 (more than 15 digits) since the internal representation is already rounded to 1 before I can even start trying to round down.
I could try to somehow parse a string containing the double but this won't help since (1/3 * 3).ToString() will already print 1 instead of 0.99...9.
Decimal does not work either since I don't want that deep precision, 14 digits are enough; but I still want that double range!
In C++, where several interval arithmetic implementations exist, this problem could be solved by telling the processor dynamically to swith its roundmode to for example "always down" or "always up". I couldn't find any way to do this in .NET.
So, do you have any ideas?
Thanks in advance!
Assume nextDown(x) is a function that returns the largest double that is less than x, and nextUp(x) is a function that returns the smallest double that is greater than x. See Get next smallest Double number for implementation ideas.
Where you would have rounded a lower bound result down, instead use the nextDown of the round-to-nearest result. Where you would have rounded an upper bound up, use the nextUp of the round-to-nearest result.
This method ensures the interval continues to contain the exact real number result. It introduces extra rounding error - in some cases the lower bound will be one ULP smaller than it should be, and/or the upper bound will be one ULP bigger. However, it is a minimal widening of the interval, much less widening than you would get working in decimal or by suppressing low significance bits.
This might be more like a long comment than a real answer.
This code returns an "interval" (I just use Tuple<,>, you can use your own Interval type) based on truncating the seven least significant bits:
static Tuple<double, double> GetMinMaxIntervalBasedOnBinaryNumbersThatAreRoundOnLastSevenBits(double number)
{
if (double.IsInfinity(number) || double.IsNaN(number))
return Tuple.Create(number, number); // maybe treat this case differently
var i = BitConverter.DoubleToInt64Bits(number);
const int numberOfBitsToClear = 7; // your seven, can change this value, must be below 52
const long precision = 1L << numberOfBitsToClear;
const long bitMask = ~(precision - 1L);
//truncate i
i &= bitMask;
return Tuple.Create(BitConverter.Int64BitsToDouble(i), BitConverter.Int64BitsToDouble(i + precision));
}
Disclaimer: I am not sure if this is useful for any purpose. In particular not sure it is useful for interval arithmetic.
With this code, GetMinMaxIntervalBasedOnBinaryNumbersThatAreRoundOnLastSevenBits(1.0 / 3.0) returns the tuple (0.333333333333329, 0.333333333333336).
This code, just like the code you ask for in your question, has the obvious "issue" that if the original value is close to (or even equal to) one of the "round" numbers we use, then the returned interval is "skewed", with the original number being close to one of the ends of the interval. For example, with input 42.0 (already round), you get out the tuple (42, 42.0000000000009).
One good thing about this code is I expect it to be extremely fast.
How do you round up to the nearest even cent?.
So, for the following decimals,
I want to round and display dollar amount:
1230.3092 => $1230.30
221.9672 => $221.96
12345.6808 => 12345.68
I've tried this
Math.Round(value, 2, MidpointRounding.ToEven)
decimal.Round(value, 2, MidpointRounding.ToEven)
but some reason it rounds up.
You want this:
(0.02m / 1.00m) * decimal.Round(value * (1.00m / 0.02m))
value * (1.00m / 0.02m) is the amount of money in terms of a "2-cents" unit. Round in that space to an integer, and then convert back to dollars.
MidpointRounding should be used to determine how you want, for example, 100.01m to round, since it is halfway between 100.00m and 100.02m.
You're trying to follow nonstandard rules for rounding, so the built-in functions won't do what you are looking for. Either overload the methods or create your own - it looks like you just need to truncate to two decimals, then add one if the result is odd (or floor then add one).
I need double value to be rounded to 2 digits.
What is preferrable?
String.Format("{0:0.00}", 123.4567); // "123.46"
Math.Round(123.4567, 2) // "123.46"
Math.Round(double,digits) with digits>0 is conceptually very unclean. But I think it should never be used. double is a binary floating point number and thus has no well-defined concept of decimal digits.
I recommend using string.Format, or just ToString("0.00") when you only need to round for decimal display purposes, and decimal.Round if you need to round the actual number(for example using it in further calculations).
Note: With decimal.Round you can specify a MidpointRounding mode. It's common to want AwayFromZero rounding, not ToEven rounding.
With ToEven rounding 0.005m gets rounded to 0.00 and 0.015 gets rounded to 0.02. That's not what most people expect.
Comparisons:
ToEven: 3.75 rounds to 3.8
ToEven: 3.85 rounds to 3.8 (That's not what most people expect)
AwayFromZero: 3.75 rounds to 3.8
AwayFromZero: 3.85 rounds to 3.9
for more information see: https://msdn.microsoft.com/en-us/library/system.math.round.aspx
They are different functions, if you need the output to be displayed, use the first one (that also forces decimals to appear). You will avoid the overhead of the inevitable .ToString() that will occur if the variable is of type double.
Note that the second one rounds the number but if it's an integer result, you will get just the integer (ie: 7 vs 7.00)
That depends on what you want to do with it.
String.Format will return a string, Math.Round(double) will return a double.
the former outputs a string, the latter a double. What's your use of the result ? The answer of this will give the answer of your question.
If you want to return this value as a string then String.Format is better and if you want to return this value as a double in that case Math.Round is better. It totally depends on your requirement.
Math.Round will not add any decimal places if there aren't any to begin with. String.Format will.
e.g.: Math.Round(2) returns 2;
String.Format("{0:0.00}",2) returns 2.00;
How would I round the following number in C# to obtain the following results.
Value : 500.0349999999
After Rounding to 2 digits after decimal : 500.04
I have tried Math.Round(Value,2, MidpointRounding.AwayFromZero); //but it returns the value 500.03 instead of 500.04
You're asking for non-standard rounding rules. The value 500.03499999999 rounded to the nearest hundredth should be 500.03. Since the thousandths digit is less than 5, the hundredths digit remains unchanged.
One way I can see to achieve your desired result is to round the number to the decimal place one smaller than what you ultimately want. Then round that result to the precision you want.
In your example, you would round the value to 3 decimal places resulting in 500.035. You would then round that to 2 decimal places which should result in 500.04 (assuming you're using MidpointRounding.AwayFromZero.
Hope that helps.
You could make it needlessly complex and wrap a variable Round(Decimal, Int32) function in a for loop. Decrement the Int32 to work it's way back to the decimal precision needed. It's a bit of work but like Eric said, you are asking for non-standard rounding rules.
Extra details: http://msdn.microsoft.com/en-us/library/ms131274.aspx
This is what I am doing, which works 99.999% of the time:
((int)(customerBatch.Amount * 100.0)).ToString()
The Amount value is a double. I am trying to write the value out in pennies to a text file for transport to a server for processing. The Amount is never more than 2 digits of precision.
If you use 580.55 for the Amount, this line of code returns 58054 as the string value.
This code runs on a web server in 64-bit.
Any ideas?
You should really use decimal for money calculations.
((int)(580.55m * 100.0m)).ToString().Dump();
You could use decimal values for accurate calculations. Double is floating point number which is not guaranteed to be precise during calculations.
I'm guessing that 580.55 is getting converted to 58054.99999999999999999999999999..., in which case int will round it down to 58054. You may want to write your own function that converts your amount to a int with some sort of rounding or threshold to make this not happen.
Try
((int)(Math.Round(customerBatch.Amount * 100.0))).ToString()
You really should not be using a double value to represent currency, due to rounding errors such as this.
Instead you might consider using integral values to represent monetary amounts, so that they are represented exactly. To represent decimals you can use a similar trick of storing 580.55 as the value 58055.
no, multiplying does not introduce rounding errors
but not all values can by represented by floating point numbers.
x.55 is one of them )
Decimal has more precision than a double. Give decimal a try.
http://msdn.microsoft.com/en-us/library/364x0z75%28VS.80%29.aspx
My suggestion would be to store the value as the integer number of pennies and take dollars_part = pennies / 100 and cents_part = pennies % 100. This will completely avoid rounding errors.
Edit: when I wrote this post, I did not see that you could not change the number format. The best answer is probably using the round method as others have suggested.
EDIT 2: As others have pointed out, it would be best to use some sort of fixed point decimal variable. This is better than my original solution because it would store the information about the location of the decimal point in the value where it belongs instead of in the code.