Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate float to %.2f format while encoding it to JSON?

Tags:

java

json

android

Let we have some float f = 52.92;. In fact, it will hold the value something like 52.91999816894531. But I want to transmit it to my web-app using json-string truncating those non-significant digits. How would I do this?

As a result, I need to obtain this json string:

{"price": 52.92}

The code I use:

float f = 52.92;
JSONObject js_price = new JSONObject();
js_price.put("price", f);
Log.d("json", js_price.toString());

Produces this ugly json:

{"price": 52.91999816894531}

Also, I need "price" to be a number format in json, not a string.

like image 301
Prizoff Avatar asked Aug 01 '12 17:08

Prizoff


Video Answer


1 Answers

It seems, that I can use the constrctor JSONObject(String json), something like this:

JSONObject js_price = JSONObject(String.format("{\"price\": %.2f}", f);

and after that I can do with this object any other json-related things...

like image 156
Prizoff Avatar answered Sep 19 '22 13:09

Prizoff