Insertion of float value into a Jsonobject

Asked

Viewed 219 times

1

I have the following situation, I have an object called Item, with a value variable in it. At the time I enter the value in the json object it changes from 1 or 2 boxes after the comma to 15 boxes after the comma.

Ex: the value is 8.9 and changes to 8.899999618530273 when placed in json.

Item:

public class Item {
    private float valor;

    public void setValor(float valor) {
        this.valor = v;
    }
    public float getValor() {
        return this.valor;
    }
}


JSONObject obj = new JSONObject();
float v = item.getValor();  // --> Aqui o valor de 'v' é 8.9
obj.put("Valor", v);   // --> Aqui após inserido no json, olhando no debugger o valor já é 8.899999618530273
...

I don’t know if that’s a normal thing JSONOBbject but causes data inconsistency.

Has some way of making the value the same as the model?

1 answer

1

One way would be to convert your float to String by formatting the decimals and using the constructor Jsonobject(String) to pass the value

Following example:

float v = item.getValor();
JSONObject obj = new JSONObject(String.format("{\"Valor\": %.2f}", v);

Another way would be by converting to String and passing via put method

 obj.put("Valor", (String.format("%.2f", v)));
  • I thought that too, but in my case you have more items to put in the json object, so I don’t know if it would be useful. Or I would have to format in a single String for all fields, which are more than 10.

  • I edited the answer in a way that might help you

  • In this case it looks like a string and not like a number. But still, thank you. I will use the value in double even, I did tests and at the time of receiving the value on the server it returns to round to 8.9 (?).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.