简体   繁体   English

Double.Parse对于“ 10.00”检索值失败

[英]Double.Parse fails for “10.00” retrieved value

The screenshot sums up the problem: 屏幕截图总结了问题:

在此处输入图片说明

I have no control over the retrieved value. 我无法控制检索到的值。 It comes in with some funky format that I can't figure out and the parsing fails even though it looks totally normal. 它带有一些我无法弄清楚的时髦格式,即使看起来很正常,解析也失败了。 Typing the value in manually works just fine. 手动输入值就可以了。

How can I "normalize" the retrieved value so Decimal.Parse does not fail? 如何“标准化”检索到的值,以使Decimal.Parse不会失败?

For reference, here is the string that fails (copied and pasted): 作为参考,以下是失败的字符串(已复制和粘贴):

"‎10.00" “ 10.00”

First I would check your regional settings to eliminate anything as simple as a difference in expected decimal separator. 首先,我将检查您的区域设置以消除任何与期望的十进制分隔符之间的差异一样简单的事情。

If that draws a blank then if the string 10.00 parses successfully then a string that looks like 10.00 but which fails to parse cannot actually be 10.00 . 如果那用空格隔开,则如果字符串10.00成功解析,则看起来10.00但未能解析的字符串实际上不能为 10.00

Inspect and determine the character code of each character of the string and confirm that it really is 10.00 and not some exotic Unicode that has the same appearance but which is actually different (which may also include characters which are not even visible when displayed). 检查并确定字符串的每个字符的字符代码,并确认它确实是10.00而不是外观相同但实际上不同的某种奇特的Unicode(它可能还包括在显示时甚至不可见的字符)。

You might have some kind of special character hidden in the string you are retrieving. 您可能在要检索的字符串中隐藏了某种特殊字符。

Try this: 尝试这个:

Double.Parse(Regex.Replace(decimalValue, @"[^0-9.,]+", ""))

You might need to add using statement for System.Text.RegularExpressions 您可能需要为System.Text.RegularExpressions添加using语句

我只替换一个有问题的字符,这是最安全的选择:

s = s.Replace("\u200E", "");

As Jeroen Mostert mentioned in a comment, there is a non-printed character in your decimalValue . 正如Jeroen Mostert在评论中提到的那样,您的decimalValue有一个非打印字符。

This is a similar question which should help you deal with that. 这是一个类似的问题,应该可以帮助您解决这个问题。

https://stackoverflow.com/a/15259355/7636764 https://stackoverflow.com/a/15259355/7636764

Edit: 编辑:

Using the the string output = new string(input.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray()); 使用string output = new string(input.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray()); part of the solution, but also include in || char.IsPunctuation(c) 解决方案的一部分,但也包含在|| char.IsPunctuation(c) || char.IsPunctuation(c) after IsDigit will get your desired result. IsDigit之后的|| char.IsPunctuation(c)将获得您想要的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM