根据 cmets 和您的问题,我猜您实际上想使用 InvariantCulture 或当前文化将 string 转换为 double。然后应该将此双精度转换为由当前文化日期时间格式信息格式化的字符串(如NumberDecimalSeparator)。
所以这个方法应该做两件事:
- 将字符串解析为双精度
- 将双精度转换为字符串
public static string ConvertToFormattedDouble(this string inputVal, IFormatProvider sourceFormatProvider = null, IFormatProvider targetFormatProvider = null)
{
if (sourceFormatProvider == null) sourceFormatProvider = NumberFormatInfo.InvariantInfo;
if (targetFormatProvider == null) targetFormatProvider = NumberFormatInfo.CurrentInfo;
if (sourceFormatProvider == targetFormatProvider)
return inputVal; // or exception?
double d;
bool isConvertable = double.TryParse(inputVal, NumberStyles.Any, sourceFormatProvider, out d);
if (isConvertable)
return d.ToString(targetFormatProvider);
else
return null; // or whatever
}
你可以这样使用:
string input = "1234.567";
string output = input.ConvertToFormattedDouble(); // "1234,567"
请注意,我扩展了字符串而不是对象。在我看来,对象的扩展是一个坏主意。你用一种几乎永远不会使用的方法污染了智能感知(尽管它也适用于string)。
更新:
如果您真的想走这条路并使用object 的扩展程序,它支持任何类型的数字作为(盒装)对象或字符串,您可以试试这个扩展程序:
public static string ConvertToFormattedDouble(this object inputVal, IFormatProvider sourceFormatProvider = null, IFormatProvider targetFormatProvider = null)
{
if (sourceFormatProvider == null) sourceFormatProvider = NumberFormatInfo.InvariantInfo;
if (targetFormatProvider == null) targetFormatProvider = NumberFormatInfo.CurrentInfo;
if (inputVal is string)
{
double d;
bool isConvertable = double.TryParse((string)inputVal, NumberStyles.Any, sourceFormatProvider, out d);
if (isConvertable)
return d.ToString(targetFormatProvider);
else
return null;
}
else if (IsNumber(inputVal))
{
decimal d = Convert.ToDecimal(inputVal, sourceFormatProvider);
return Decimal.ToDouble(d).ToString(targetFormatProvider);
}
else
return null;
}
public static bool IsNumber(this object value)
{
return value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is int
|| value is uint
|| value is long
|| value is ulong
|| value is float
|| value is double
|| value is decimal;
}
用法:
object input = 1234.56745765677656578d;
string output = input.ConvertToFormattedDouble(); // "1234,56745765678"