I'm using a ASP.Net Web API v2 to retrieve a list of products from the database. Using this web api i am obtaining a JSON that contains the data for my view and displaying it using jquery. However, the significant digits are being removed from the Price property upon getting the JSON.
For example -
<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>
This is the XML from the API. And my Jquery Code:
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);
});
});
});
Now console.log and the td tag with item.Price are both displaying 996 instead of 996.0000. Is there any way, i can prevent the significant digits from being removed?
It's standard behaviour to remove trailing decimal zeroes from float values. If you need to retain them, you can use toFixed()
, like this:
$('<td>').text(item.Price.toFixed(4))
One thing to note however is that toFixed()
outputs a string, so you will need to convert it back to a float if you need to perform any mathematical operations on it.
尝试这个
$('<td>').text(parseFloat(item.Price).toFixed(4)),
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.