Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.Round vs String.Format

Tags:

c#

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"
like image 568
Oleg Vazhnev Avatar asked Dec 06 '11 09:12

Oleg Vazhnev


2 Answers

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

like image 119
CodesInChaos Avatar answered Oct 03 '22 17:10

CodesInChaos


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)

like image 27
Mihalis Bagos Avatar answered Oct 03 '22 16:10

Mihalis Bagos