2010-01-26 82 views
0

我有以下方法:字符串格式問題

public static string ReturnFormat(string input, int maxLength, int decimalPrecision, char formatChar) 
    { 
    string[] format = new string[2]; 
    string[] inputs = new string[2]; 

    inputs = input.Split(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]); 

    if (input.Length > maxLength) 
    { 
    int offset = 0; 
    int counter = 0; 

    if (inputs[0].Length > maxLength - (1 + decimalPrecision)) 
    { 
    offset = maxLength - (1 + decimalPrecision); 
    } 
    else 
    offset = inputs[0].Length; 

    for (int i = 0; i < offset; i++) 
    { 
    format[0] += formatChar; 

    if (counter < decimalPrecision) 
    { 
     format[1] += '0'; 
     counter++; 
    } 
    } 

    System.Windows.Forms.MessageBox.Show("{0:" + format[0] + "." + format[1] + "}"); 
    return String.Format(CultureInfo.CurrentCulture, "{0:" + format[0] + "." + format[1] + "}", input); 
    } 
    else 
    return input; 
    } 

哪個說我使用的是:

ReturnFormat("12.3456789011243", 10, 2, '#') // format is {0:##.00} // output 12.3456789011243 
ReturnFormat("12345678901.1243", 10, 2, '#') // format is {0:#######.00} // output 12345678901.1243 

現在,我的問題是,輸入字符串未格式化好,還是格式strig似乎沒問題。 任何想法我做錯了什麼?

+0

什麼是你想要的輸出? – 2010-01-26 08:15:27

+0

輸出我想成爲1234568.12 – wikiz 2010-01-26 08:23:22

+1

另外,這是一個非常奇怪的格式函數,我很難弄清楚什麼時候會需要。 – 2010-01-26 08:26:17

回答

2

你的輸入是一個字符串不是雙精度型,所以它被格式化爲一個字符串:在這種情況下格式化不知道小數位數。

您可以使用Double.Parse()將字符串轉換爲Double值,但請注意使用正確的文化。

另一件事,有沒有在兩種情況下使用更自然格式{0:0.00}的具體原因?如果你真的想用數字佔位符,那麼#是可以的,否則0是最好的。

測試的解決方案(注意它截斷和不圓),我需要一些時間來了解什麼是真正想要的東西:

public static string ReturnFormat(string input, int maxLength, int decimalPrecision) 
{ 
    if (input.Length <= maxLength) 
     return input; 
    Char separator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]; 
    string[] inputs = input.Split(separator); 
    // NB: truncating rather than rounding 
    if (inputs[1].Length > decimalPrecision) 
     inputs[1] = inputs[1].Substring(0, decimalPrecision); 
    int digits = (maxLength - decimalPrecision - 1); 
    // NB: truncating rather than rounding, adding ~ to signalize the 
    // presence of missing significant digits 
    if (inputs[0].Length > digits) 
     inputs[0] = inputs[0].Substring(0, digits-1) + "~"; 
    return inputs[0] + separator + inputs[1]; 
} 
+0

行, 所以我用Double.Parse(),它在第一種情況下工作正常(12.3456789011243返回12.35),但不適合第二(12345678901.1243返回相同) 儘管如此,在第二種情況下,我猜((0:#######。00})格式是可以的。 – wikiz 2010-01-26 08:20:53

+0

#是佔位符,它是一個陷阱,請參閱http://color-of-code.de/index.php?option=com_content&view=article&id=58:c-format-strings&catid=38:programming&Itemid=66上的我的備忘單 – jdehaan 2010-01-26 08:25:58

+0

不要猶豫,聯繫我的其他問題或關於格式的意見,我儘量保持該表最新。我認爲你會更喜歡0.00作爲格式字符串,而不是執行復雜的格式字符串計算。 – jdehaan 2010-01-26 08:27:18