Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from string to double removes trailing zeros

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

This works for most numbers but it gives an unwanted output when the double contains a trailing zero the parseDouble method is removing it. I don't want this to be removed.

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 yields the output:

-15.21 45.801 124.5

But I want the trailing zeros. The problem with using a formatted line is that I would have to specify the floating point accuracy that I want when printing values, but I don't have any specific desire to make the numbers accurate to a certain point, merely leave the zeros alone if they are there.

Am I approaching this wrong?

like image 318
leigero Avatar asked Feb 15 '23 02:02

leigero


2 Answers

You could store a reference to the original string and print that instead of the parsed double

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

Result:

-15.210 45.801 124.50
like image 121
twj Avatar answered Feb 17 '23 12:02

twj


You could use BigDecimal to handle the values. BigDecimal preserves trailing zeroes.

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 + " ");
}
like image 38
Viktor Seifert Avatar answered Feb 17 '23 12:02

Viktor Seifert