Math.Round vs String.Format

前端 未结 6 1718
天命终不由人
天命终不由人 2021-01-18 18:24

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)                 


        
相关标签:
6条回答
  • 2021-01-18 18:46

    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)

    0 讨论(0)
  • 2021-01-18 18:52

    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

    0 讨论(0)
  • 2021-01-18 18:59

    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;

    0 讨论(0)
  • 2021-01-18 19:00

    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.

    0 讨论(0)
  • 2021-01-18 19:04

    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.

    0 讨论(0)
  • 2021-01-18 19:09

    That depends on what you want to do with it.

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

    0 讨论(0)
提交回复
热议问题