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)
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)
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:
for more information see: https://msdn.microsoft.com/en-us/library/system.math.round.aspx
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;
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.
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.
That depends on what you want to do with it.
String.Format
will return a string, Math.Round(double)
will return a double.