C#中将字符串转换为浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11202673/
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
Converting String To Float in C#
提问by Mehmet
I am converting a string like "41.00027357629127", and I am using;
我正在转换像“41.00027357629127”这样的字符串,我正在使用;
Convert.ToSingle("41.00027357629127");
or
或者
float.Parse("41.00027357629127");
These methods return 4.10002732E+15.
这些方法返回4.10002732E+15。
When I convert to float I want "41.00027357629127". This string should be the same...
当我转换为浮动时,我想要“41.00027357629127”。这个字符串应该是一样的...
采纳答案by Matthew Watson
Your thread's locale is set to one in which the decimal mark is "," instead of ".".
您线程的语言环境设置为十进制标记为“,”而不是“.”的语言环境。
Try using this:
尝试使用这个:
float.Parse("41.00027357629127", CultureInfo.InvariantCulture.NumberFormat);
Note, however, that a float cannot hold that many digits of precision. You would have to use double or Decimal to do so.
但是请注意,浮点数不能保存那么多位数的精度。您必须使用 double 或 Decimal 才能这样做。
回答by ABH
You can double.Parse("41.00027357629127");
你可以 double.Parse("41.00027357629127");
回答by jpe
The precision of floatis 7 digits. If you want to keep the whole lot, you need to use the doubletype that keeps 15-16 digits. Regarding formatting, look at a post about formatting doubles. And you need to worry about decimal separators in C#.
float的精度为 7 位。如果要保留整批,则需要使用保留15-16位数字的double类型。关于格式化,请看一篇关于格式化 doubles的帖子。并且您需要担心C# 中的小数点分隔符。
回答by Ozgur Dogus
Use Convert.ToDouble("41.00027357629127");
用 Convert.ToDouble("41.00027357629127");
回答by Tigran
First, it is just a presentationof the floatnumber you see in the debugger. The realvalue is approximately exact (as much as it's possible).
首先,它只是您在调试器中看到的数字的表示float。的真正价值约为准确(就像它是可能的)。
Note: Use alwaysCultureInfoinformation when dealing with floating point numbers versus strings.
注意:在处理浮点数与字符串时,始终使用CultureInfo信息。
float.Parse("41.00027357629127",
System.Globalization.CultureInfo.InvariantCulture);
This is just an example; choose an appropriate culture for your case.
这只是一个例子;为您的案例选择合适的文化。
回答by Learner
You can use parsing with double instead of float to get more precision value.
您可以使用 double 代替 float 进行解析以获得更精确的值。
回答by user4292249
You can use the following:
您可以使用以下内容:
float asd = (float) Convert.ToDouble("41.00027357629127");

