简体   繁体   English

神秘的字符串进行双重转换

[英]Mysterious String to double conversion

I am tying to convert a string to double in C#, wherein i face a situation, 我想在C#中将字符串转换为double,但是遇到这种情况,

String of value "6,," gets converted to double whereas the string "6++" or a number with successive chars throws an error which is understandable. "6,,"的字符串将转换为双精度型,而字符串"6++"或带有连续字符的数字则抛出一个可以理解的错误。

Please clarify why the first string gets converted? 请说明为什么第一个字符串会被转换?

The comma is used as a thousands separator in some cultures, so it's acceptable for it to be present in a numeric string. 逗号在某些区域性中用作千位分隔符,因此以数字字符串形式出现是可以接受的。 The same cannot be said for a plus sign. 加号不能说相同。

To clarify, "+6" would be valid, since you can represent a positive number explicitly with the plus sign. 为了澄清,“ + 6”将是有效的,因为您可以使用加号显式表示一个正数。 However, "6+" is not a recognised numeric format in any culture that I am aware of. 但是,在我所知的任何区域中,“ 6+”都不是公认的数字格式。 Similarly, while "6," could be considered valid, ",6" probably isn't unless you specifically use a culture where the comma is a decimal separator. 类似地,虽然“ 6,”可以被认为是有效的,但是除非您专门使用逗号为小数点分隔符的区域性,否则“,6”可能不是有效的。

Since , is the thousands separator for the invariant culture, the parser just ignores them before the decimal point. 由于,是不变区域性的千位分隔符,因此解析器只会在小数点忽略它们。 You can also parse "6,4,55.23" and it yields 6455.23 . 您还可以解析"6,4,55.23" ,结果为6455.23

Trying to parse a number with a comma after the decimal point, however, results in an error. 但是,尝试用小数点的逗号来解析数字会导致错误。

In the documentation doe Double.Parse , the following rules are given (paraphrased): 在文档doe Double.Parse ,给出了以下规则(解释为):

[ws][sign][integral-digits[,]]integral-digits[.[fractional-digits]][E[sign]exponential-digits][ws] [WS] [符号] [积分位数[,]]积分位数[[小数位] [E [符号]指数位数] [WS]

  • Runs of integral-digits can be partitioned by a group-separator symbol. 整数位数可以用组分隔符分隔。 For example, in some cultures a comma (,) separates groups of thousands 例如,在某些文化中,逗号(,)分隔成千上万的组

So there's no requirement that the thousands separator have three digits after it (or between consecutive separators) 因此,不要求千位分隔符后面(或连续的分隔符之间)三位数

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

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