473,583 Members | 2,875 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Rounding decimal (fast)

Consider a rounding up function:

public static decimal RoundUp(decimal val, decimal round)
{
return ((decimal)Math. Ceiling((double )(val/round)))*round;
}
Math.Ceiling (and Math.Floor for RoundDown) only take double,s so we
need to cast twice. Is there a better way?

--
Wal
http://www.vooose.com

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #1
4 15372
How about

decimal rounded = Decimal.Round(o riginalValue, numPlaces);

?

Nov 17 '05 #2
vooose <no****@microso ft.com> wrote:
Consider a rounding up function:

public static decimal RoundUp(decimal val, decimal round)
{
return ((decimal)Math. Ceiling((double )(val/round)))*round;
}
Math.Ceiling (and Math.Floor for RoundDown) only take double,s so we
need to cast twice. Is there a better way?


Aside from Bruce's point - do you have any evidence that this is
actually the bottleneck in your application? It's always worth waiting
until you know you have a problem before trying micro-optimisation like
this. (In this particular case, Bruce's solution is much better - it's
much more readable as well as potentially faster.)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #3
Thanks for your reply. According to the doc, Decimal.Round rounds to the
nearest. (see below)

I need one that roundsUp and roundsDown !

quote
Remarks
When d is exactly halfway between two rounded values, the result is the
rounded value that has an even digit in the far right decimal position.
For example, when rounded to two decimals, the value 2.345 becomes 2.34
and the value 2.355 becomes 2.36. This process is known as rounding
toward even, or rounding to nearest.


--
Wal
http://www.vooose.com

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #4
Rounds up:

decimal rounded = Decimal.Round(o riginalValue, 3);
if (rounded != originalValue)
{
rounded = Decimal.Round(o riginalValue + 0.0005, 3);
}

rounds down:

decimal rounded = Decimal.Round(o riginalValue, 3)
if (rounded != originalValue)
{
rounded = Decimal.Round(o riginalValue - 0.0005m, 3);
}

Not terribly pretty, but it will work. This sort of thing is easier
where the rounding system always takes the half (e.g. 0.5) _up_, not to
the nearest even digit. It's the latter that requires the first round
attempt and the test, unfortunately.

However, your original code looks as though you are trying to round to
the left of the decimal place, e.g. "to the next higher thousand" or
"to the next higher hundred." In this case, it gets easier:

decimal nextHigherThous and = ((int)(original Value / 1000m)) * 1000m;
if (nextHigherThou sand != originalValue)
{
nextHigherThous and += 1000m;
}

Since to cast to (int) truncates rather than rounding, the first
calculation will either give you the original value back (if it's
already a multiple of 1000) or round down. The test determines whether
the original value was a multiple of 1000 and, if it wasn't, adds 1000
to produce a "round up" effect. This will cost you one cast to int to
perform the truncation, and one (invisible) coercion from int back to
decimal.

Nov 17 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
6730
by: Norvin Laudon | last post by:
Hi, Can somebody explain the following, from the MSDN documentation for the "System.Convert.ToInt32(double)" function <quote> Return Value value rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is
4
7820
by: spebola | last post by:
I am using vb.net 2003 professional and I get the following results when using the round method: dim Amount as decimal = 180.255 Amount = Amount.Round(Amount, 2) Amount now contains 180.25. I need it to contain 180.26. Any ideas?
11
6633
by: cj | last post by:
Lets assume all calculations are done with decimal data types so things are as precise as possible. When it comes to the final rounding to cut a check to pay dividends for example in VB rounding seems to be done like this 3.435 = 3.44 3.445 = 3.44 Dim decNbr1 As Decimal
6
2241
by: shaqattack1992-newsgroups | last post by:
Hello Everyone, I'm using the following on a form in my database: =(-Int(-Sum((IIf(=Yes,((*)+()), (((*)+)*1.06))*100))))/100 In this case, I want to calculate a total for an order. If the LineTaxExempt field is checked (meaning tax exempt), the total is
29
3156
by: Marco | last post by:
Hello, I have : float f = 36.09999999; When I do : char cf; sprintf(cf,"%0.03lf", f); I get : 36.100
5
8000
by: Spoon | last post by:
Hello everyone, I don't understand how the lrint() function works. long lrint(double x); The function returns the nearest long integer to x, consistent with the current rounding mode. It raises an invalid floating-point exception if the magnitude of the rounded value is too large to represent. And it raises an inexact floating-point...
206
13200
by: md | last post by:
Hi Does any body know, how to round a double value with a specific number of digits after the decimal points? A function like this: RoundMyDouble (double &value, short numberOfPrecisions) It then updates the value with numberOfPrecisions after the decimal
20
4976
by: jacob navia | last post by:
Hi "How can I round a number to x decimal places" ? This question keeps appearing. I would propose the following solution #include <float.h> #include <math.h>
30
29513
by: bdsatish | last post by:
The built-in function round( ) will always "round up", that is 1.5 is rounded to 2.0 and 2.5 is rounded to 3.0. If I want to round to the nearest even, that is my_round(1.5) = 2 # As expected my_round(2.5) = 2 # Not 3, which is an odd num I'm interested in rounding numbers of the form "x.5" depending upon whether x is odd...
0
7811
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8159
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7922
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8185
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5689
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5366
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3811
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1416
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1147
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.