Get the difference in digits between two numbers
Parry
For a simple command line tool, I want to draw a simple graph showing some points and their y-axis values. For the y-axis labels, I want to print the level of the current "row", for example:
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| ||||||||||||||||||||||||||||||
But what can happen is that the maximum value has more digits than the minimum value:
1000,00| |
666,67| | |
333,33| |||
0,01|||||
So how can I get the difference in numbers between the max and min values so that leading spaces are added?
1000,00| |
666,67| | |
333,33| |||
0,01|||||
Matthew
Quick and 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
In your loop:
System.out.format("%"+smax+".2f", value);
Edit, from @EJP's comment
In fact, using log10
max is both cleaner and more efficient . It will give you a power of 10, so the number of digits (minus one) will be used. Although the first solution is simple (counting characters, which is what we want), this solution is better in every other way:
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
In your loop:
System.out.format(fmt, value);