将所有小数从动态JSON舍入到2位小数

时间:2015-05-14 20:50:31

标签: javascript jquery json decimal

我正在创建一个从JSON文件动态提取数据的表,我需要能够将值更改为两位小数。这是否可能基于我已有的代码? 我想做的例子:

- 7次更改为7.00

- 3922.2更改为3922.20

- 89.2823更改为89.28

提前非常感谢!

这是我的HTML:

<table id="reportTable" class="reportTable">
    <th>Timer Name</th>
    <th>Daily Percentile 90th</th>
    <th>Daily Percentile 50th</th>  
    <th>Min Percentile 90th</th>
    <th>Max Percentile 90th</th>
    <th>Daily Average</th>
</table>

这是我的JQuery和Javascript:

//THIS CODE GETS THE JSON, ALPHABETIZES THE INFO, AND POPULATES THE TABLE.
var information = $.ajax({
type: "GET",
url: "http://websiteIgetmyJSONfrom.com",
dataType: "json",
success: function (information) {
    information.sort( function( a, b ) {
        a = a.timerName.toLowerCase();
        b = b.timerName.toLowerCase();

        return a < b ? -1 : a > b ? 1 : 0;
    });

    $.each(information, function(i, item) {
        var $tr = $('<tr class="clickable">').append(
            $('<td align="left">').text(item.timerName),
            $('<td>').text(item.daily_percentile_90th),
            $('<td>').text(item.daily_percentile_50th),             
            $('<td>').text(item.min_percentile_90th),
            $('<td>').text(item.max_percentile_90th),
            $('<td>').text(item.daily_average)).appendTo('#reportTable');
    });
},
error: function(){ alert("FAILED TO LOAD JSON"); }
});

返回JSON的示例:

{
    "daily_percentile_90th": 4430.6,
    "min_percentile_90th": 1598.8,
    "max_percentile_90th": 5518.9,
    "daily_percentile_50th": 3793.5,
    "timerName": "Temple:Shared",
    "daily_average": 3745.16
},
{
    "daily_percentile_90th": 1904.2,
    "min_percentile_90th": 634.4,
    "max_percentile_90th": 3296.6,
    "daily_percentile_50th": 1103.5,
    "timerName": "Search:Catalog",
    "daily_average": 1332.82
},
{
    "daily_percentile_90th": 780,
    "min_percentile_90th": 0.8,
    "max_percentile_90th": 780,
    "daily_percentile_50th": 239,
    "timerName": "FT:Person:Ordinances",
    "daily_average": 397.324
},

1 个答案:

答案 0 :(得分:4)

使用javascript numToFixed函数:

var num = 5.56789;
var n = num.toFixed(2);

n的结果将是:

5.57