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?
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
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 + " ");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With