JSONArray(jsonstring) drops decimal if 0 - java

I have a json string with floating values:
{"foo":10.0,"bar":12.005}
I need to convert it using JSONObject(jsonstring) and I need to retain the decimals, but the json array drops them if they are zero. The result looks like
{"foo":10,"bar":12.005}
I expected that i could provide additional parameters to control the data type but according to
https://developer.android.com/reference/org/json/JSONObject
there is no such option. I also searched google and stackoverflow but i cannot find any similar problems.

JSONObject always treats everything as Objects so they must be converted to float by parsing it.
String json = "{\"foo\":10.0}";
try{
JSONObject jo = new JSONObject(json);
float f = Float.parseFloat(jo.get("foo").toString());
System.out.println(f);
}
catch(Exception e){
// Some parsing exception occurs
}
Hope this solves the issue.
Also JSONObject supports methods for getting the items in various datatype like double, int, boolean
double d = jo.getDouble("foo");
System.out.println(d); // gave me 10.0
Similarly we have
int i = getInt("name"); // which returns an integer
boolean b = getBoolean("name"); // Automatically parses

There's no way to get the number of digits from JSON.parse or eval. Even if IBM's decimal proposal had been adopted by the EcmaScript committee, the number is still going to be parsed to an IEEE 754 float.
Take a look a http://code.google.com/p/json-sans-eval/source/browse/trunk/src/json_sans_eval.js for a simple JSON parser that you can modify to keep precision info.
solution already provided here
How to prevent removing decimal point when parsing JSON?

This is the expected behaviour.
The DECIMAL field is converted to the JSON NUMBER data type.
This type trims trailing zeros by default.
It's up to the client/receiver of the JSON to decide how many decimal places it needs to show and set the correct display format.

For the 10.0 it will add value as an integer in JSON, if you want it with decimal then first you need to convert it as a string and then you need to put string value in JSON.
val foo = 10.0
val bar = 12.005
val strFoo = foo.toString();
val jsonObject = JSONObject()
jsonObject.put("foo",strFoo)
jsonObject.put("bar", bar)

I guess, it's not a problem of JSON array, rather language's type conversion from float to int.
Use something similar to this to format float to string String.format("%,.2f", val);
Edit
The Workflow will go as follows:
if(Math.ceil(val)==val){ //a number with no fractional points
String str = String.format("%,.2f", val);
}
else //use_the_floating_number_as_usual

Related

How can I format a String number to have commas in Kotlin?

i have this code to calculate distance from 2 points(lat,lon)
val distance = distanceInKm(3.140853,21.422510,101.693207,39.826168)
val number3digits:Double = String.format("%-10.4f%n%n", distance).toDouble()
distancetomakkah.text = "$number3digits"
but i'm getting this output:
10891.3684
and i want the output to be like this:
10,891
i tried to change the format to:
("%-10.4f%n%n"),("%,d") and many others but i keep getting this error
f != java.lang.string
what am i doing wrong here?
String.format("%-10.4f%n%n", distance).toDouble()
Your format is not being applied. After formatting your returned value of distanceInKm as a String, you are calling toDouble, undoing any formatting you did.
distancetomakkah.text = "$number3digits"
number3digits is a Double, and default formatting is applied when you use string interpolation to assign .text.
Try
String.format("%-,10.4f%n%n", distance);
The result is of type String
That wouldn't be portable of course, since the , is not used in some Locales

How to remove scientific notation from double for longest double value

I am experiencing a problem in Double value manipulation.
Lets take,
Double d = new Double(123456789987654321123456789d);
System.out.println(d);
The output is :
1.2345678912345678E35
But I want,
123456789987654321123456789
The complete digit without any notation.
I have tried all permutation using BigDecimal, BigInteger and so and so.
Note: I want to populate into JSON so please don't suggest just a print statement.
I have already read :
How to Avoid Scientific Notation in Double?
Formatting a double and not rounding off
Try this BigDecimal::toPlainString:
BigDecimal d = new BigDecimal("123456789987654321123456789");
String result = d.toPlainString();
Output of d is :
123456789987654321123456789
To populated to JSon there are many ways, I'm not sure what you want exactly, but maybe this can help you How to create JSON Object using String?:
BigDecimal d = new BigDecimal("123456789987654321123456789");
JSONObject myObject = new JSONObject();
myObject.put("number", d.toPlainString());
You can try this
String str = String.format("%.0f", d);
Note that max digits a double can hold is ~17, so 123456789987654321123456789 will rounded

json parse long double values without auto format

I'm trying to parse json array with some values.
Got some problems with long values like that "0.00009800".
I've tried jsonObject.getDouble and getString on it - it returns 9.8E-5.
Also tried BigDecimal with same results.
It should has simple solution which i'm missing.
tmp.high24h = Double.valueOf(e.getString("High"));
tmp.low24h = java.math.BigDecimal.valueOf(e.getDouble("Low")).doubleValue();
9.8E-5 is the expected value. It represents 9.8 * 10^(-5).
Always use String datatype for larger decimal values. After the conversion of json string to java object, convert it to BigDecimal value by passing the string as an argument in BigDecimal constructor.
Got it:
tmp.high24h = e.getDouble("High");
String test = String.format(Locale.US, "%.5f", tmp.high24h);

How to remove decimal in java without removing the remaining digits

Is there any method to remove the . in java into a double value?
Example :
56.11124
to
5611124
I don't think there's a mathematical way to find out how many decimals there are in a double. You can convert to a String, replace the dot, and then convert it back:
Double.parseDouble(Double.toString(56.11124).replace(".", ""));
Be careful of overflows when you parse the result though!
Here's one way to do it,
First, convert the double to a string. Then, call replace to replace . with an empty string. After that, parse the result into an int:
double d = 5.1;
String doubleString = Double.toString(5.1);
String removedDot = doubleString.replace(".", "");
int result = Integer.parseInt(removedDot);
Obviously, this wouldn't work if the double's string representation is in scientific notation like 5e16. This also does not work on integral double values, like 5, as its string representation is 5.0.
doubles are inaccurate by nature. 5 and 5.0 are the same value. This is why you can't really do this kind of operation. Do you expect different results for a and b?
double a = 5;
double b = 5.0;
If you do, then you can't really do this, since there is no way of knowing what the programmer wrote exactly at runtime.
This might work
class Example {
public static void main(String[] args) {
double val = 56.1112;
while( (double)((int)val) != val )
{
val *= 10;
}
System.out.printf( "%.0f", val );
}
}
Output: 561112
This works by casting the double to int which truncates the floating information 56.11124 => 56. While the values aren't equal you multiply it by the base to push the . out. I don't know if this is the best way.
You can convert to BigDecimal and use the unscaledValue method:
BigInteger unscaled = new BigDecimal(myDouble).unscaledValue();
Depending on your intended output, you might also use BigDecimal#valueof(double) to create the intermediate BigDecimal.
Javadoc for BigDecimal#new(double)
Javadoc for BigDecimal#valueOf(double)
Javadoc for BigDecimal#unscaledValue()
You can convert it to a String and remove the . and convert it back to double something like
double value = 56.11124;
value = Double.valueOf(("" + value).replace(".", "")).doubleValue();
This will return 5611124.0 since its a double you will have the floating point. You can convert it to an int, but you have to take care of the possible overflow. Otherwise it would look like this
int normalized = (int) value;

Exponential values vs double ( big decimal conversion already used)

i am using following function to format the double value to x.xx , but after that the result value started to end up with exponential value ( i have already read the answers which are advising to use the DecimalFormat or to plain text () methods but every where the system is giving error to change the types ...return types i am lost a bit now
can some one please help me in following method tweaks so that the returning values can be displayed as normal number instead of 3.343E32
Please note that the following function FD is used many times in code so i want to change it here only so i dont have to apply the formatting each and every results / variable..
public double fd(double x) {
BigDecimal bd_tax = new BigDecimal(x);
BigDecimal formated = bd_tax.setScale(2, BigDecimal.ROUND_UP);
x = Double.valueOf(formated.doubleValue());
return x;
}
You say, "...to format the double value...", but there is no code in your example that formats anything. Your fd(x) function takes a double as its argument, and it returns a double. It doesn't do anything else.
If your numbers really are in the neighborhood of 3.343E32, Then they're going to have a lot of digits: 33 digits before the decimal point. Is that what you were expecting?
Suggest you look at String.format() if you are trying to turn the double value into human readable text. Something like this, perhaps:
public String fd(double x) {
return String.format("%.2f", x);
}

Categories

Resources