2012-07-25 26 views
0

我有一個由用戶25|35|40輸入的字符串。我已將100=25+35+40以下的任何數字格式化爲此格式。例如,如何在java中自定義數字格式?

5 --> 05|00|00 
30 --> 25|05|00 
65 --> 25|35|05 

應保持25 | 35 | 40的順序。這與日期格式MM:dd:yyyy類似,因爲我們知道月份不能超過12,日期不能超過31,但這裏可以出現任何值。其位置上的值決定最大值。又如,

如果用戶字符串是40|110|2500|350

5 --> 05|000|0000|000 
100 --> 40|060|0000|000 
450 --> 40|110|0300|000 
2900 --> 40|110|2500|250 

如果該數量超過總3000=40+110+2500+350,我可以使其作爲number -= 3000。 目前我正在嘗試使用自定義代碼格式化它將檢查數量並將創建所需的輸出字符串。在java中有沒有內置格式的API?

+0

你能解釋一下你格式化好一點?最後一行可能應該是'35 | 25 | 05'嗎? – aioobe 2012-07-25 08:24:40

+0

似乎是一個非常具體的商業案例......無法看到任何API,因爲%和 - 字符串連接足以完成這項工作。你爲什麼要這樣來格式化,也許它會幫助我們找到一個工具。 – poussma 2012-07-25 08:26:21

+0

請問您如何從30/65到三位數字? – vainolo 2012-07-25 08:26:25

回答

0

這樣的特定用例沒有公共API。這是解決這個問題的一種方法:

int num = 65; 
int i1 = num > 25 ? 25 : num; 
int i2 = num < 25 ? 0 : num > 60 ? 35 : num - 25; 
int i3 = num < 60 ? 0 : num - 60; 
System.out.format("%02d|%02d|%02d", i1, i2, i3); 

打印

25|35|05 

或者,概括它:

public static String format(String format, int num) { 
    String[] split = format.split("\\|"); 
    int numLeft = num; 
    StringBuilder result = new StringBuilder(); 
    for (int i = 0; i < split.length; i++) { 
     int boundary = Integer.parseInt(split[i]); 
     int number = Math.min(numLeft, boundary); 
     if (result.length() > 0) { 
      result.append('|'); 
     } 
     result.append(leftPad(number, split[i].length())); 
     numLeft = Math.max(0, numLeft - boundary); 
    } 
    return result.toString(); 
} 

private static String leftPad(int number, int length) { 
    StringBuilder sb = new StringBuilder(); 
    sb.append(number); 
    while (sb.length() < length) { 
     sb.insert(0, '0'); 
    } 
    return sb.toString(); 
} 

public static void main(String[] args) { 
    String result = format("25|35|40", 65); 
    System.out.println(result); 
} 
+0

謝謝!但是這僅限於三段和兩個十進制格式。 – Ahamed 2012-07-25 08:46:43

+0

@Ahamed:是的,沒有看到更新的要求。現在它適用於您指定的任何格式。 – Keppil 2012-07-25 08:57:08

+0

我已經更新了我的問題以清楚地解釋邏輯。謝謝!!! – Ahamed 2012-07-25 08:57:46