How to convert to double with 2 precision - string

2019-01-17 20:17发布

I want to convert this string: 0.55000000000000004 to this double: 0.55. How to do that?

3条回答
爷、活的狠高调
2楼-- · 2019-01-17 20:51

There is no double 0.55 - the number cannot be accurately represented as a binary fraction. Which is probably the reason why you got that long string in the first place. You should probably be using the decimal type instead of double.

Read The Floating-Point Guide to understand why.

查看更多
迷人小祖宗
3楼-- · 2019-01-17 20:55

Is a string or a double? If it is a string:

double d = double.Parse(s,CultureInfo.InvariantCulture);
string s=string.Format("{0:0.00}",d);

if it is already a double just format using the second line.

查看更多
劳资没心,怎么记你
4楼-- · 2019-01-17 21:00

you can use this code to reduce precision part:

double m = Math.Round(0.55000000000000004,2);

Result would be : 0.55

查看更多
登录 后发表回答