使用ajax舍入浮点值

时间:2013-03-01 11:18:29

标签: php jquery

使用json我得到的值,从尝试使用以下脚本舍入值:

          function onLoad(){
            var output = $('#product');
            var id = getUrlVars()["cPath"];
            $.ajax({
                url: 'getprice.php?cPath='+id,
                data : {type : 'product'},
                dataType: 'jsonp',
                jsonp: 'jsoncallback',
                timeout: 5000,
                success: function(data){
          $.each(data, function(c,prd){

              var price  =Math.round(prd.products_price,2);




                           var product = '<span class="normalprice">$' + price + '</span>' ;
                           output.append(product);
                            }

                        });
                    output.listview("refresh");
                        //data loaded
                    },
                    });
        }

// OutPut NEEDS

   prd.products_price=450.2500
   price=$450.25

也尝试这种格式但不起作用:

            1.  var num = Math.val(prd.products_price);
                var price = num.toFixed(2);

3 个答案:

答案 0 :(得分:1)

var num = Math.val(prd.products_price); 
var num = parseFloat(num);
var price=num.toFixed(2));

答案 1 :(得分:1)

var price = prd.products_price;
var product = price.formatMoney(0, "")

Number.prototype.formatMoney = function(places, symbol, thousand, decimal) {
        places = !isNaN(places = Math.abs(places)) ? places : 2;
        symbol = symbol !== undefined ? symbol : "$";
        thousand = thousand || ",";
        decimal = decimal || ".";
        var number = this;
        var negative = number < 0 ? "-" : "";
        var i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "";
        var j = (j = i.length) > 3 ? j % 3 : 0;

        return symbol
                + negative
                + (j ? i.substr(0, j) + thousand : "")
                + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand)
                + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
    }

答案 2 :(得分:0)

试试这个:

var price = parseFloat(prd.products_price).toFixed(2);