获得2个数字之间的数字差异

时间:2016-04-15 16:03:02

标签: java

对于一个简单的命令行工具,我想绘制一个简单的图形,显示一些点及其y轴值。对于y轴标记,我想打印当前“行”的级别,如:

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|||||

1 个答案:

答案 0 :(得分:3)

快速' N'脏:

<button type="button" onclick="alert('Hello world!')">Click Me!</button>

在你的循环中:

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

编辑,来自@ EJP的评论

在最大值上使用System.out.format("%"+smax+".2f", value); 确实更干净,更有效。它将为您提供10的幂,因此将使用的数字(减1)。虽然第一个解决方案很简单(计算字符,这是我们想要的直线),但这个解决方案在其他方面都更好:

log10

在你的循环中:

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