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)
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