JSON return conversion error for JAVA Class

3

I have a java class

public class PRODUTO extends SugarRecord implements Parcelable {

  private float id_pro;

  public PRODUTO(float id_pro){
    this.id_pro = id_pro;
  }

  public float getId_pro() {
    return id_pro;
  }
  public void setId_pro(float id_pro) {
    this.id_pro = id_pro;
  }
  // PARCELABLE
  public PRODUTO(Parcel parcel) {
    setId_pro(parcel.readFloat());
  }
  @Override
  public int describeContents() {
    return 0;
  }
  @Override
  public void writeToParcel(Parcel parcel, int i) {
    parcel.writeFloat(getId_pro());
  }
  ...
}

A php API that returns me a JSON from my mysql base, in it comes id_pro , for example: 257895

But always add automatically a ". 0" at the end of the variable AFTER ASSIGNING THE CLASS,

I've checked the return data, it comes right from JSON, but at the time of assigning the class it stays like this, on the mysql base I have a bigint field that I've already moved to float also to test and did not. But when I use String in the class for id_pro , it correctly gets 257895, but I wanted to work directly on the object's format.

I use a HttpURLConnection for the request.

Does anyone have an idea of what I'm doing wrong?

    
asked by anonymous 16.05.2018 / 07:11

1 answer

3

The float in Java represents a floating-point number with 32-bit precision whenever you write the number, unless you are doing something like Console.WriteLine() with a format string , it will always write .0 if it does not have decimal places to indicate that it does not really have decimal places.

The solution will be to use a data type that represents an integer because the ID is always an integer and for iusso you can use either int or long - or their wrappers, Int and Long . Just note that in Java int uses 32 bits and long uses 64, so long despite spending more memory - easy to understand because it represents twice the bits of a int - also represents many, many more numbers:

 int | -2^31 a +2^31 -1 |             -2,147,483,648 a 2,147,483,647
long | -2^63 a +2^63 -1 | -9,223,372,036,854,775,808 a 9,223,372,036,854,775,807

Useful resources

  

Fun fact : With a long , if your function increments every second nano, it would take 292 years to overflow ( !!! ) source a>

    
16.05.2018 / 11:36