对于一个简单的命令行工具,我想绘制一个简单的图形,显示一些点及其 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|||||

最佳答案

快速与肮脏:

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

关于java - 获取两个数字之间的位数差异,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36651897/

10-13 03:04