-4

I've a set of double values and they're split by the decimal point and a 0 is added in front.

e.g. input:1229.5 - expected output:0.1229

However if the input value has a 0 in the end e.g 1270.2 the output becomes 0.127 whereas it should be 0.1270.

Here is my code:

static double[] data = new double[] {6754.6,7235.9,5432.2,1270.2,5413.6,1099,1018};

public static void main(String[] args) {
    for(int i=0;i<data.length; i++){
        String outputStr = String.valueOf(data[i]);
        String[] fileNameSplit = outputStr.split("\\.");
        fileNameSplit[0] = "0."+fileNameSplit[0];
        double newData = Double.valueOf(fileNameSplit[0]);
        System.out.println(newData);
    }
}
PRCube
  • 566
  • 2
  • 6
  • 19

1 Answers1

0

You must make distinction between an object to it's string representation.

A double is not even a decimal number, when you print it in the standard output it gets converted to a decimal number and then formatted.

Java does that implicitly and converts any type to it's default string representation before printing it to the console.

So as many have said, you have to format your output if you need so.

minus
  • 2,646
  • 15
  • 18