簡體   English   中英

從JSON獲取正確的float值在jQuery中

[英]Getting proper float value in Jquery from JSON

我正在使用ASP.Net Web API v2從數據庫中檢索產品列表。 使用此Web API,我將獲取一個包含我的視圖數據的JSON,並使用jquery顯示它。 但是,在獲取JSON時,將從Price屬性中刪除了有效數字。

例如 -

<ArrayOfProductModel xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/ProductManagement.Models">
<ProductModel>
<Description>
Get ready to channel your inner dark knight with this epic Batman tee!
</Description>
<Id>1</Id>
<Imagepath>/Images/559276_1.jpg</Imagepath>
<Name>Batman T-Shirt (Men's)</Name>
<Price>996.0000</Price>
</ProductModel>

這是API中的XML。 而我的Jquery代碼:

var uri = '/api/Product';

$(document).ready(function () {
   $.getJSON(uri).done(function (data) {
    $.each(data, function (key, item) {
        console.log(item.Price);
        var img='<img src='+item.Imagepath+' alt="productImage" height="150px" width="150px">'
        var $tr=$('<tr>').append(
            $('<td>').text(item.Id),
            $('<td>').text(item.Name),
            $('<td>').text(item.Description),
            $('<td>').html(img),
            $('<td>').text(item.Price),
        );
        $('#productlist').append($tr);
    });
  });
});

現在console.log和帶有item.Price的td標簽都顯示996,而不是996.0000。 有什么辦法可以防止重要數字被刪除?

從浮點值中刪除尾隨的十進制零是標准行為。 如果需要保留它們,則可以使用toFixed() ,如下所示:

$('<td>').text(item.Price.toFixed(4))

但是要注意的一件事是toFixed()輸出一個字符串,因此如果需要對其執行任何數學運算,則需要將其轉換回浮點數。

嘗試這個

$('<td>').text(parseFloat(item.Price).toFixed(4)),

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM