Convert from string to double remove trailing zeros

I am trying to convert a list of doubles from a string format to a double format. I did this by putting them on a list and using a method Double.parseDouble(string).

This works for most numbers, but gives undesirable output, when double contains a trailing zero, the method parseDoubleremoves it. I do not want this to be deleted.

String[] values = {"124.50", "45.801", "-15.210"};
List<Double> nums = new ArrayList<Double>();

for(String s: values)
nums.add(Double.parseDouble(s));
Collections.sort(nums);

for(Double d: nums){
    System.out.print(d + " ");
}

This gives the result:

-15.21 45.801 124.5

But I need trailing zeros. The problem with using a formatted string is that I will need to specify the floating point precision that I want when printing the values, but I have no specific desire to make the number accurate to a specific point, just leave only zeros if they are there .

Am I approaching this wrong?

+3
4

,

public static void main(String[] args) {
    String[] values = {"124.50", "45.801", "-15.210"};
    List<MyDouble> nums = new ArrayList<MyDouble>();

    for(String s: values)
    nums.add(new MyDouble(s));
    Collections.sort(nums);

    for(MyDouble d: nums){
        System.out.print(d + " ");
    }
}

static class MyDouble implements Comparable<MyDouble> {
    final double val;
    final String string;
    MyDouble(String str) {
        string = str;
        val = Double.parseDouble(str);
    }

    @Override
    public String toString() {
        return string;
    }

    @Override
    public int compareTo(MyDouble o) {
        return (int) (val - o.val);
    }
}

:

-15.210 45.801 124.50
+7

n , :

final DecimalFormat df = new DecimalFormat("#.000");
for (Double d : nums) {
    System.out.print(df.format(d) + " ");
}

, , @BrianRoach, , , , .

final String[] values = {"124.50", "45.801", "-15.210"};
final List<Double> nums = new ArrayList<>();
final List<Double> bkpNums = new ArrayList<>();

for (final String s : values) {
    double d = Double.parseDouble(s);
    nums.add(d);
    bkpNums.add(d);
}
Collections.sort(nums);

for (Double d : nums) {
    System.out.print(values[bkpNums.indexOf(d)] + " ");
}
0

You can use BigDecimalto process values. BigDecimalkeeps trailing zeros.

String[] values = {"124.50", "45.801", "-15.210"};
List<BigDecimal> nums = new ArrayList<BigDecimal>();

for(String s: values)
    nums.add(new BigDecimal(s));
Collections.sort(nums);

for(BigDecimal d: nums) {
    System.out.print(d + " ");
}
0
source

Try using:

DecimalFormat df = new DecimalFormat("###.#");

when printing numbers

-1
source

All Articles