Math.Round vs String.Format

I need a double value rounded to two digits. Which is preferable?

String.Format("{0:0.00}", 123.4567); // "123.46" Math.Round(123.4567, 2) // "123.46" 
+4
source share
5 answers

These are different functions, if you need output for display, use the first one (which also makes decimals appear). You will avoid the overhead of the inevitable .ToString (), which will occur if the variable is of type double.

Note that the second rounds the number, but if it is an integer result, you get just an integer (i.e.: 7 vs 7.00)

+6
source

Math.Round(double,digits) with numbers> 0 is conceptually very unclean. But I think it should never be used. double is a binary floating-point number and therefore does not have a clear concept of decimal digits.

I recommend using string.Format or just ToString("0.00") when you only need to round for decimal display, 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 MidpointRounding . AwayFromZero rounding is usually required, not ToEven .

With ToEven rounding is 0.005m rounded to 0.00 and 0.015 rounded to 0.02 . This is not what most people expect.

Comparisons:

  • ToEven: 3.75 rounds to 3.8
  • ToEven: 3.85 rounds to 3.8 (This is 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

+10
source

It depends on what you want to do with it.

String.Format will return a string, Math.Round(double) will return double.

+4
source

the first displays a line, the second doubles. What is your use of the result? The answer to this question will answer your question.

+1
source

if you want to return this value as a string, then String.Format is better, and if you want to return this value as double, in this case Math.Round is better. Its completely up to your requirement.

0
source

Source: https://habr.com/ru/post/1384864/


All Articles