我有一个像1.5%"这样的字符串,想把它转换成双精度值.
I have a string like "1.5%" and want to convert it to double value.
可以通过以下方式简单地完成:
It can be done simple with following:
public static double FromPercentageString(this string value)
{
return double.Parse(value.SubString(0, value.Length - 1)) / 100;
}
但我不想使用这种解析方式.
but I don't want to use this parsing approach.
还有其他方法可以使用 IFormatProvider 或类似的方法吗?
Is any other approach with IFormatProvider or something like this?
如果您关心捕获格式错误,我会使用 TrimEnd 而不是 Replace.替换将允许格式错误通过而不被发现.
If you care about catching formatting errors, I would use TrimEnd rather than Replace. Replace would allow formatting errors to pass undetected.
var num = decimal.Parse( value.TrimEnd( new char[] { '%', ' ' } ) ) / 100M;
这将确保该值必须是某个十进制数字,后跟任意数量的空格和百分号,即,它必须至少以正确格式的值开头.更准确地说,您可能希望在%"上进行拆分,而不是删除空条目,然后确保只有两个结果,第二个是空的.第一个应该是要转换的值.
This will ensure that the value must be some decimal number followed by any number of spaces and percent signs, i.e, it must at least start with a value in the proper format. To be more precise you might want to split on '%', not removing empty entries, then make sure that there are only two results and the second is empty. The first should be the value to convert.
var pieces = value.Split( '%' );
if (pieces.Length > 2 || !string.IsNullOrEmpty(pieces[1]))
{
... some error handling ...
}
var num = decimal.Parse( pieces[0] ) / 100M;
使用 Replace 将允许您成功并错误地 IMO 解析以下内容:
Using Replace will allow you to successfully, and wrongfully IMO, parse things like:
除了1.5%
这篇关于如何将百分比字符串转换为双倍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!