How to prevent JSONObject from json.jar converting decimal numbers to string in double

Using JSONObject to read json response from server. The server returns some decimal number. Normal numbers are not a problem, but the problem arises when there is a decimal number of the form 0.00068 . Numbers, such as 0.00068 , are automatically stored in the Double object, and when an attempt is made to get such a number, the "computerized scientific notation" of this number is returned, that is 6.8E4, even if the number is available as a double using the getDouble(index) method or as a String with the getString(index) method.

We tried this method of converting a double value to a string, but eliminated this tecinique, because some positive rounding was added when Double converted to BigDecimal . This can be eliminated by rounding when scaling to BigDecimal.ROUND_CEILING . But I do not want to scale and I want to have the original values, since the actual value is a small decimal number, and the server guarantees that after the decimal point the number will not exceed 6 digits.

 BigDecimal big = new BigDecimal(new Double(0.00680)); System.out.println(big.toPlainString()); //0.006799999999999999621136392846665330580435693264007568359375 System.out.println(big.setScale(15, BigDecimal.ROUND_DOWN)); //0.006799999999999 

Could there be some way to get the actual String value of Double, which is the number 0.00680 without scaling, or can we prevent JSONObject interpreting the numbers in their respective number classes.

Thanks in advance.

+4
source share
2 answers

Unrelated to the JSON library used, you should not use the BigDecimal constructor with a double parameter, since it uses the exact decimal representation of a binary binary floating element, the value of a dot

Use the static valueOf method instead, since it correctly uses the string value of the double and therefore rounds it.

When double should be used as the source for BigDecimal, note that this constructor provides accurate conversion; it does not give the same result as converting double to String using the Double.toString(double) method, and then using the BigDecimal(String) constructor. To get this result, use the static method valueOf(double) .

However, for very large or small numbers, parsing on a double can already introduce rounding errors, in which case the only solution would be to use another JSON library that supports parsing numbers like BigDecimals.

+5
source
 String str = BigDecimal.valueOf(Obj.getDouble("StringName")).toPlainString(); 
0
source

Source: https://habr.com/ru/post/1389046/


All Articles