Home > Mobile >  JSON decoding removing decimal trailing zeros
JSON decoding removing decimal trailing zeros

Time:10-17

I have a JsonArray and need to convert it into Array of objects. Below is the code I am using. response - json response

ArrayList<TestClass> list = new ArrayList<>();
            JsonArray jsonArray = new JsonArray(response);
            jsonArray.forEach(o -> {
              JsonObject jsonObject = new JsonObject(o.toString());
              // logic to transform into desired class and add to list
            });
Json.encode(list.toArray());

Problem is when converting to string for decimals, trailing zeros are getting removed. example : if value is 4.50 it's just returning 4.5 if it's 3.00, 3 is getting returned. Looking to return raw data as it is. Any pointers on fixing this

CodePudding user response:

Trailing zeros can be printed if you treat decimal as String, for that you can use DecimalFormat or String.format(…). As we know adding trailing zero to a number after decimal doesn’t impact the value of the number. If you are going to use the converted value in computation later in the program then better to not to worry about trailing zeros. On the other hand if you’re going to use this value to be displayed on screen somewhere then let the client handle it.

CodePudding user response:

Java floating point types don't have a way to preserve a trailing zeros.

For example, when you run this code snippet:

double d1 = 4.5;
double d2 = 4.50;
System.out.println(d1 == d2);

it will print true ... because 4.5 and 4.50 are the same number. Both in Java, and in mathematics.

And they also mean the same thing in JSON.

If you really want to preserve the trailing zeros, then:

  • In JSON you must represent the number as a string; i.e. put quotes around it.
  • In Java you must store it in a String variable. Which is going to make computation problematic.

Q: Would it be possible to faithfully preserve the trailing zeros AND do arithmetic?

A: I don't know of an existing Java type / class that does this.

One of the problems is what happens with division. For example, the exact representation of 1.0 / 3.0 would entail an infinite number of significant digits. Which is problematic.

I guess, if you had a mathematical model of floating point numbers that could represent a Real number and an uncertainty, AND that model was implementable (e.g. didn't involve problems such as indefinitely large representations, factorization, etc), then such a Java class would be possible.

But in the meantime, a better approach would be to review your requirement. Why do you need to preserve the trailing zeros? It doesn't make sense from a straight-forward mathematical perspective. Is there some other reason for doing it?

  • Related