具有文化格式的双重解析
我有一个双数作为字符串。号码是
202.667,40
这是 202667.4
我如何解析这个字符串来获取值,例如: Double.Parse("202.667,40",? 这里是什么),或者任何其他方法来获取值都会很棒。谢谢
I have a double number as string. The number is
202.667,40
Which is 202667.4
How can I parse this string to get the value like: Double.Parse("202.667,40",?what here), or any other method to get the value would be great. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
首先,您需要知道这个数字来自哪种文化,然后:
如果您想使用当前线程文化进行解析,默认情况下是为当前用户设置的文化:
First, you need to know which culture this number is from, then:
If you want to parse using the current thread culture, which by default is the one set for the current user:
我想我已经找到了一个不需要文化的解决方案。使用 NumberFormatInfo 您可以强制使用某种格式,无论文化如何:
然后:
输出:
202667,4
当然,这个输出(内部 toString())可能因文化而异(!)
请注意,将输入更改为“202,667.40”将导致解析错误,因此格式应与您预期的输入匹配。
希望这对某人有帮助..
I think i have found a solution which does not require a culture. Using a NumberFormatInfo you can force a format, no matter the culture:
Then later:
Outputs:
202667,4
Of course, this output (inner toString()) might differ per Culture(!)
Note that changing the input to "202,667.40" will result in a parse error, so the format should match your expected input.
Hope this helps someone..
您可以使用 Double.Parse(your_number, CultureInfo.CurrentCulture) 并使用 Thread.CurrentThread.CurrentCulture 相应地设置 CurrentCulture。
示例:
then later
请注意,如果您将区域性显式分配给 CurrentThread,则它仅适用于该线程。
You could use Double.Parse(your_number, CultureInfo.CurrentCulture) and set CurrentCulture accordingly with Thread.CurrentThread.CurrentCulture.
Example:
then later
Note that if you explicitly assign the culture to the CurrentThread, it only applies to that thread.
我不必在所有解析中指定区域设置,而是更喜欢设置应用程序范围的区域设置,尽管如果字符串格式在应用程序中不一致,这可能不起作用。
在应用程序的开头定义它将使所有双精度解析都期望逗号作为小数分隔符。
Instead of having to specify a locale in all parses, I prefer to set an application wide locale, although if string formats are not consistent across the app, this might not work.
Defining this at the begining of your application will make all double parses expect a comma as the decimal delimiter.
http://www.erikschierboom.com/2014/09/01 /数字与文化/
http://www.erikschierboom.com/2014/09/01/numbers-and-culture/
为了获得更大的灵活性,您可以设置 NumberDecimalSeparator
For more flexibility you can set NumberDecimalSeparator
使用字符串所在的任何文化,而不是 de-DE。
Instead of de-DE use whatever culture the string is in.