2

I'm putting numbers in a JTable. If I put a number that's too long, it will truncate with an ellipsis. I'd like to override this behavior, so that the numbers are formatted so that they fit into the cells. This would involve putting certain numbers into scientific notation. I also don't want leading or trailing zeroes; if the number isn't the entire width of the cell, it's acceptable.

String#substring(int, int) doesn't work because that wouldn't work with scientific notation or would lose information 0.0000000000000001would become 0 and not 1e-16.

String#format(String, Object...) with the %g format doesn't work because it leaves trailing/leading zeroes, and doesn't include the scientific notation in the digit count.

I also looked at DecimalFormat, but couldn't find anything that allowed setting the number of characters.

A few examples of the intended behavior (with the max number of characters being 11):

3 -> 3
0.0000000000000001 -> 1e-16
1234567891011121314 -> 1.234568e18
3.1415926535897932384626433832 -> 3.141592654
0.00010001000100010001 -> 0.00010001

How could I accomplish this?

Thanks in advance!

ricky3350
  • 1,710
  • 3
  • 20
  • 35
  • 1
    Why would `0.00010001` not be written `1.0001e-4`? From how many digits do you want the scientific notation? – Tunaki Dec 06 '15 at 19:40
  • @Tunaki Forgive my ambiguity; I want to express numbers with the most information possible. `1.0001e-4` has less information than `0.00010001`. – ricky3350 Dec 06 '15 at 19:59
  • 1
    How so? It's the same number, there is no lost information – Tunaki Dec 06 '15 at 20:00
  • [Here is an excellent post about this](http://stackoverflow.com/questions/2944822/format-double-value-in-scientific-notation). I'll post an answer inspired from it. – Yassin Hajaj Dec 06 '15 at 20:02
  • @Tunaki Sorry, there is less information _available to the user_ when they are reading the value, – ricky3350 Dec 06 '15 at 20:42

1 Answers1

1

This could help you, it is inspired from the post I linked in the comments. This will format the String and delete the leading zeros.

Main

String[] nums = {"000000003","0.000000000000001","1234567891011121314","3.1415926535897932384626433832","0.00010001000100010001"};
for (int i = 0 ; i < nums.length ; i++){
    System.out.println(format(nums[i].replaceAll("^0*", "")));
}

format Method

public static String format(String s){
    if (s.length() <= 11) return s;
    return String.format("%6.5e", Double.valueOf(s));
}

Output

3
1,00000e-15
1,23457e+18
3,14159e+00
1,00010e-04
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
  • Looks good... but `1,00000e-15` still has trailing zeroes, and `3,14159e+00` should be in standard notation. I could do some regex stuff, and then add digits back; is there a better way? – ricky3350 Dec 06 '15 at 20:46
  • @ricky3350 Yes I think it is possible by modifying the method a bit. I'll check what I'm able to do. – Yassin Hajaj Dec 06 '15 at 20:49