bipin singh
bipin singh

Reputation: 7

Read Decimal value from JSON response in java

We have an API which returns response below:

{
"Amount": 10.2300,
"name": "Test"
}

Amount will have 4 places after decimal. We need to validate that decimal places should be 4 places, below is the code:

String strres = response.asString();
System.out.println("strres" + strres);

JSONObject data = new JSONObject(strres);
float myFloatValue = BigDecimal.valueOf(data.getDouble("Amount")).floatValue();
System.out.println("The Amount " + myFloatValue);

After execution we get : myFloatValue = 10.23 only, and not 10.2300 hence decimal places is less than 4. Please suggest how can we read without loss of decimal places.

sAmount = response.jsonPath().get("Amount").toString()

String[] splitter = sAmount.toString().split("\\.");
splitter[0].length(); 
splitter[1].length();

When storing to String variable, also getting same value: 10.23

Upvotes: -2

Views: 1282

Answers (1)

gokareless
gokareless

Reputation: 1253

You can do so:

//...
  float myFloatValue = BigDecimal.valueOf(23.0).floatValue();
  String formatted = String.format("%.4f", myFloatValue);
  System.out.println(formatted);
//...

Upvotes: 2

Related Questions