如何转换比例串翻番? [英] How to convert percentage string to double?
问题描述
我有像1.5%的字符串,并希望将其转换为double值。
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而不是取代。更换将使格式错误漏过。
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;
这将确保该值必须是一些十进制数后跟任意数量的空格和百分号,即,它至少必须在正确的格式值开始。为了你可能想拆就'%',不删除空条目,然后确保只有两个结果,第二个是空的更precise。首先应该是要转换的值。
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;
使用更换可以让你成功,并错误地IMO,解析之类的东西:
Using Replace will allow you to successfully, and wrongfully IMO, parse things like:
- 1.5%
- 1%。5
- 1%,5
在addtion到 1.5%
这篇关于如何转换比例串翻番?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!