2012-11-02 25 views
2

这似乎是一个非常愚蠢的问题,但我只是没有设法解决它。下面是代码:String.Format函数不起作用

private string[] ConvertToCurrency(string[] costs) 
{ 
    int count = costs.Length; 

    for (int i = 0; i < count - 1; i++) 
    { 
     costs[i] = String.Format("{0:C}", costs[i]); 
    } 

    return costs; 
} 

,我想到的是,输出应该是我存储在我的字符串数组的数字将被格式化为货币,但他们完全没有改变,当他们出来的另一端。

我不知道为什么会发生这种情况,并尝试了一些其他方法来格式化它,但没有。

+6

为什么for循环终止于count-1而不是count? – Rik

回答

8

您应该这样做,{0:C}用于货币格式,它将应用于数字值。

costs[i] = String.Format("{0:C}", Convert.ToDecimal(costs[i])); 
0

这是因为参数string[] costs类型是字符串,所以它不会像预期的那样格式化数字。您必须将参数类型更改为数字(int,long,float,double等),或者在格式化之前必须将该值转换为数字类型。在以前的答案

var val = Convert.ToInt32(costs[i]); 
costs[i] = String.Format("Value is: {0:C}", val); 
0

建筑,这似乎是引进LINQ的理想场所:

private IEnumerable<String> ConvertToCurrency(IEnumerable<String> costs) 
{ 
return costs.Select(c => String.Format("{0:C}", Convert.ToDecimal(c))); 
} 

所以在这种情况下,它仍然会在完全相同的方式阵列工作,但使逻辑访问列表/队列等...如果您想急于执行,请在选择后添加ToArray()

5

充分说明:

当你有一个像你的字串{0:C}一个项目,那么C部分是格式字符串。引述the documentation

如果formatString存在,由格式条款中引用的论据 必须实现IFormattable接口(我的重点)

一个IFormattable对象像doubledecimalan overloadToString需要一个字符串,这可能是"C"你的情况。所以它翻译成类似yourFormattableThing.ToString("C", null)

但是,当你看the documentation for string,你看到一个string(如您的costs[i])不IFormattablestring不具有ToString这需要在格式字符串。所以你违反了我上面引用的“必须实现”。

String.Format选择忽略您的C部分,而不是提出例外。

所以,你有什么问题的解释。

现在,为了使事情的工作,如果你的字符串是一个真正的数字,转换/其解析到一个IFormattable对象像decimaldouble,然后用"C"格式字符串的数值类型。

0
public static class StringExtensions 
{ 
    /// <summary> 
    /// Formats a string using the string.Format(string, params object[]) 
    /// </summary> 
    /// <param name="helper">The string with the format.</param> 
    /// <param name="args">The value args.</param> 
    /// <returns>The formatted string with the args mended in.</returns> 
    public static string Mend(this string helper, params object[] args) => string.Format(helper, args); 

} 

//使用方法: “零:{0},一:{1},二:{2}”。修补( “0”, “1”, “2”);