简体   繁体   中英

GSON - Json to Java parsing - How to keep the trailing zero

import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson; 
import com.google.gson.GsonBuilder;  

public class StudentMain { 
   public static void main(String[] args) { 
      String jsonString = "{\"name\":\"XYZ\", \"percentage\":95.90}"; 

      GsonBuilder builder = new GsonBuilder(); 
      builder.setPrettyPrinting(); 

      Gson gson = builder.create(); 
      Student student = gson.fromJson(jsonString, Student.class); 
      System.out.println(student.getPercentage());  
   } 
} 

    package com.json;

    class Student { 
           private String name; 
           private double percentage; 
           public Student(){} 

           public String getName() { 
              return name; 
           }

           public void setName(String name) { 
              this.name = name; 
           } 

           public double getPercentage() { 
              return percentage; 
           }

           public void setPercentage(double percentage) { 
              this.percentage = percentage; 
           }

           public String toString() { 
              return "Student [ name: "+name+", age: "+ percentage+ " ]"; 
           }  
        }

It is displying 95.9 but I wanted to display 95.90. Can someone please help?

You can replace toString body with following code snippet:

public String toString() { 
    return String.format("Student [ name: %s, age: %.02f]", name, percentage)
}

So you don't need to change double to String

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM