|
-
February 9th, 2012, 07:52 AM
#7
Re: Basic Question about Math.Round and {0:C}
 Originally Posted by jdearing
[...] I just added the Math.Round(finalCost, 3) as I though it should round to 1.13 when I saw the original 1.124864 [...]
If you check the docs for Math.Round(double, int), you'll see this description for the second parameter:
The number of fractional digits in the return value.
So, it refers to the number of decimal places after the decimal point. That's why your program rounded to 1.125.
 Originally Posted by jdearing
Just a question, which way would you use in a Production Environment?
Depends. Generally, if you wanted to round numbers for various calculations, like in a physics-based simulation, you would use Math.Round().
However, note that Math.Round() and {0:C} have different purposes.
Math.Round() changes the actual numerical data value, while {0:C} only changes the string representation of the value, without ever changing the original data.
By using a Math.Round(double, int, MidpointRounding) overload, and setting the last parameter to AwayFromZero will get you the same behavior as with {0:C}, in terms of how the rounding is done, but the difference in whether the original data is affected or not still remains.
So, it's like this: if you just want to round the number for display, so that a user (human) can read it with more ease, use {0:C}, and leave the original number unchanged, maintaining the more accurate, higher precision value internally. The user usually only cares for the value to be precise up to a number of decimal places.
If, OTOH, you need to work with rounded values in your internal calculation, then use Math.Round(). For example, you might want to do this if you're performing calculations with doubles, so that you can have greater precision, but ultimately only need an integer value. Use Math.Round() if you need rounding in your implementation regardless of whether you're gonna display the result as text or not.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|