2013-12-15 58 views
0

我有一个问题显示值为浮动序列化/反序列化与json与gson。相反,它会删除浮点数,而不是显示fx。 745.0显示745.任何想法为什么?parseFloat gson json字符串

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

的JavaScript只有一个称为Number的单一数字类型。它与Java double类型保持相同的范围。 JSON也是一样。

当您将值连接到字符串时,将在号码上调用toString()方法。 Number.toString()如何工作在中定义9.8.1 ToString应用于数字类型the standard

基本上,如果它们不重要,它将不会打印小数位。从控制台:

> 1234.0000.toString() 
"1234" 

如果您要格式化显示货币,则需要考虑字符串。如果您在客户端执行此操作,您将需要类似jQuery的this plugin,或者请参阅here for Java。

+0

我只能使用v.rate.toFixed(2) –