.net 如何以 2 个精度转换为双精度 - 点后的字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4997085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 15:15:38  来源:igfitidea点击:

How to convert to double with 2 precision - string after dot?

.netc#-4.0doubleprecision

提问by MonsterMMORPG

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

我想把这个字符串: 转换0.55000000000000004成这个 double: 0.55。怎么做?

回答by mjyazdani

you can use this code to reduce precision part:

您可以使用此代码来降低精度部分:

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

Result would be : 0.55

结果将是:0.55

回答by Felice Pollano

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.

如果它已经是使用第二行的双格式。

回答by Michael Borgwardt

There is nodouble 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 decimaltype instead of double.

没有双0.55 -数量不能准确地表示为二进制分数。这可能是你首先得到那么长字符串的原因。您可能应该使用decimal类型而不是double.

Read The Floating-Point Guideto understand why.

阅读浮点指南以了解原因。