2016-04-15 61 views
3

對於一個簡單的命令行工具,我想繪製一個簡單的圖形來顯示一些點和它們的y軸值。對於y軸的標籤我要打印的當前「行」之類的級別:獲取2個數字之間的數字計數差異

55,09| | 
54,90| || 
54,70| || 
54,51| || 
54,32| || 
54,13| || 
53,94| || 
53,75| || 
53,56| || 
53,37| ||| 
53,18| |||     | | 
52,99| |||   |  || | 
52,80| |||   | |  || | 
52,61| |||   || |  ||| | 
52,42| ||||||  || | | |||| || 
52,23| ||||||  |||| | |||| || 
52,04| ||||||  |||| | |||| ||| 
51,85| ||||||  |||| | |||| ||| 
51,66| ||||||  |||| ||| |||| ||| 
51,47| ||||||  ||||||||| |||||||| 
51,28| ||||||  |||||||||||||||||| 
51,09| ||||||  |||||||||||||||||| 
50,90| ||||||  ||||||||||||||||||| 
50,71| ||||||  ||||||||||||||||||| 
50,52| ||||||| ||||||||||||||||||| 
50,33| ||||||| ||||||||||||||||||| 
50,14| ||||||| ||||||||||||||||||||| 
49,95| ||||||| ||||||||||||||||||||| 
49,76| |||||||| ||||||||||||||||||||| 
49,28| |||||||||||||||||||||||||||||| 

但它可能發生的最大值比最小值多個數字:

1000,00| | 
666,67| | | 
333,33| ||| 
0,01||||| 

所以我怎樣才能得到最大和最小值之間的數字差異,所以我可以添加前導空格?

1000,00| | 
666,67| | | 
333,33| ||| 
    0,01||||| 
+0

看到的NumberFormat – ControlAltDel

+1

使用'字符串.format()'或'System.out.format()'和一個類似於'%7.2f'的模式作爲數字,其中'7'表示數字的寬度,'2'表示小數部分的寬度。 –

+0

考慮到你的數據是有序的,爲什麼不把所有的東西都填充到與最高值相同的長度呢? – flakes

回答

3

Quick'n'dirty:

double max = getMaximum(); // Get your maximum Y value 
int smax = String.format("%.2f", max).length(); // Print as a string and get number of characters 

在你的循環:

System.out.format("%"+smax+".2f", value); 

編輯,從@ EJP的評論

這的確是既清潔和在最大值上使用log10效率更高。它會給你10的權力,因此將使用的數字(減一)。雖然第一種方法是直接的(算上字符,這是筆直我們想要的),該解決方案在所有其他方面更好:

double max = getMaximum(); 
int ndigits = (int)Math.floor(Math.log10(max)) + 1; 
int precision = 2; // Number of digits after decimal point 
String fmt = "%"+(ndigits+1+precision)+"."+precision+"f"; // "%x.pf", x is the TOTAL length, including the point and precision digits 

在你的循環:

System.out.format(fmt, value); 
+2

以log10的底線會簡單得多。 – EJP

+0

@EJP事實上,儘管我認爲你的意思是天花板+1,所以ceil(log10(1000.0))= 4。當我得到一個編譯器正確地測試它時,我會更新我的答案。 – Matthieu

+1

不,我真正的意思是floor(log10))+ 1或ceil(log10))。你在這裏提出的建議仍然是錯誤的。它給9個2位數,11個3個。 – EJP

相關問題