2013-12-15 2 views
0

gson에서 json으로 serialize/deserialize 할 때 float 값을 표시하는 데 문제가 있습니다. 대신 fx를 표시하는 대신 부동 소수점을 제거합니다. 745.0은 디스플레이 745입니다. 어떤 아이디어일까요?parseFloat gson json string

public String execute(HttpServletRequest request, HttpServletResponse response, CurrencyClient client) { 

    String currency = client.findAll_JSON(String.class); 

    Gson gson = new Gson(); 

    Currency[] currencies = gson.fromJson(currency, Currency[].class); 
    System.out.println("currencies " + currencies[0].getRate()); 
    response.setContentType("application/json;charset=UTF-8"); 
    try (PrintWriter pw = response.getWriter()) { 
     //System.out.println("JSON " + currencies); 

     MyObject myObject = new MyObject(); 
     for (Object c : currencies) { 
      myObject.add((gson.toJson(c))); 
     } 
     System.out.println("value of rate: " + gson.toJson(myObject.getCurrencies())); 
     pw.println(gson.toJson(myObject)); 

     pw.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    return super.execute(request); 
} 

}

클래스 MyObject를 {

ArrayList<Object> currencies = new ArrayList<Object>(); 

public MyObject() { 
} 
public void add(Object e){ 
    this.currencies.add(e); 
} 
public Object getCurrencies() { 
    return currencies; 
} 

public void setCurrencies(ArrayList<Object> currencies) { 
    this.currencies = currencies; 
} 

그리고 클라이언트 측 코드 : 여기 은 백엔드 코드는 명령 패턴을 통해 생성되는

  $(document).ready(function() { 



        $.ajax({ 

         url: "Controller", 
         cache: false, 
         dataType: "json", 
         data: {command: 'getCurrencyRates'}, 
         success: function(data) { 

          $.each(data.currencies, function(index, value) { 

           var v = JSON.parse(value); 


           console.log(rate); 

           $("<tr><td>" + v.code + "</td><td>" + v.description + "</td><td>" + v.rate + "</td></tr>") 
             .appendTo($("table")); 
          }); 
         } 

        }); 
       }); 

답변

0

자바 스크립트 만 Number이라는 단일 숫자 유형이 있습니다. Java double 유형과 동일한 범위를 유지합니다. JSON도 마찬가지입니다.

문자열과 값을 연결하면 숫자에 toString() 메서드가 호출됩니다. Number.toString() 작동 방식은 에 정의되어 있습니다. 9.8.1 숫자 유형에 적용된 ToStringthe standard입니다.

기본적으로 중요하지 않은 경우 소수점 이하는 인쇄되지 않습니다. 콘솔에서 :

> 1234.0000.toString() 
"1234" 

표시 할 통화의 서식을 지정하려면 문자열을 고려해야합니다. 클라이언트에서이 작업을 수행하거나 자바 용 here을 보려면 jQuery에 대해 this plugin과 같은 것이 필요합니다.

+0

그냥 v.rate.toFixed (2)를 사용할 수 있습니다. –