Sorting a double value of an object within an arrayList

To use a Comparator: Collections.sort(myList, new Comparator<Chromosome>() { @Override public int compare(Chromosome c1, Chromosome c2) { return Double.compare(c1.getScore(), c2.getScore()); } }); If you plan on sorting numerous Lists in this way I would suggest having Chromosome implement the Comparable interface (in which case you could simply call Collections.sort(myList), without the need of specifying an explicit … Read more

How to hide leading zero in printf

The C standard says that for the f and F floating point format specifiers: If a decimal-point character appears, at least one digit appears before it. I think that if you don’t want a zero to appear before the decimal point, you’ll probably have to do something like use snprintf() to format the number into … Read more

Java Double to String conversion without formatting

Use a fixed NumberFormat (specifically a DecimalFormat): double value = getValue(); String str = new DecimalFormat(“#”).format(value); alternatively simply cast to int (or long if the range of values it too big): String str = String.valueOf((long) value); But then again: why do you have an integer value (i.e. a “whole” number) in a double variable in … Read more

How do I limit the number of decimals printed for a double?

Use a DecimalFormatter: double number = 0.9999999999999; DecimalFormat numberFormat = new DecimalFormat(“#.00″); System.out.println(numberFormat.format(number)); Will give you “0.99”. You can add or subtract 0 on the right side to get more or less decimals. Or use ‘#’ on the right to make the additional digits optional, as in with #.## (0.30) would drop the trailing 0 … Read more

Double subtraction precision issue

double is internally stored as a fraction in binary — like 1/4 + 1/8 + 1/16 + … The value 0.005 — or the value 1.435 — cannot be stored as an exact fraction in binary, so double cannot store the exact value 0.005, and the subtracted value isn’t quite exact. If you care about … Read more

How to return a value from try, catch, and finally?

To return a value when using try/catch you can use a temporary variable, e.g. public static double add(String[] values) { double sum = 0.0; try { int length = values.length; double arrayValues[] = new double[length]; for(int i = 0; i < length; i++) { arrayValues[i] = Double.parseDouble(values[i]); sum += arrayValues[i]; } } catch(NumberFormatException e) { … Read more

tech