Convert string to double with 2 digit after decimal separator

别来无恙 提交于 2019-12-03 16:07:02

Doubles can't exactly represent 16.9. I suggest you convert it to decimal instead:

string s = "16.9";
decimal m = Decimal.Parse(s) * 100;

double d = (double)m;

You might just want to keep using the decimal instead of the double, since you say you'll be using it for monetary purposes. Remember that decimal is intended to exactly represent decimal numbers that fit in its precision, while double will only exactly represent binary numbers that do.

Math.Round(number, 1)

Edit I got the wrong question - the rounding problems are inherent to a floating point type (float, double). You should use decimal for this.

The best solution for not going be crazy is: string s = "16.9";

For ,/. double d = Convert.ToDouble(s.Replace(',','.'),System.Globalization.CultureInfo.InvariantCulture);

For rounding: Convert.ToDouble((d).ToString("F2"));

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!