Inserting float value into a JSONObject

1

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

Ex: 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 do not know if this is something normal for JSONOBbject to do, but it causes data inconsistency.

Is there a way to make the value the same as the template?

    
asked by anonymous 30.08.2017 / 20:18

1 answer

1

One way would be to convert your float to String by formatting the decimal places and using the JSONObject (String) to pass the value

Here's an example:

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

Another way would be to convert to String and passing via put method

 obj.put("Valor", (String.format("%.2f", v)));
    
30.08.2017 / 21:13