首页 > 解决方案 > 如何在 AJAX 中将值格式化为货币或百分比

问题描述

将值格式化为百分比或货币Ajax并显示为的最佳方法是Table什么?

我目前正在开发一个应用程序,它的 Money值SQL Server3569.093美元569.09以及.Table

我试过这个但仍然没有帮助。

这是 JS 我的代码:

function loadMarginBelow21() {
    $.ajax({
        url: "/Dashboard/MarginBelow21",
        type: "GET",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (result) {
            var html = '';
            $.each(result, function (key, item) {
                html += '<tr>';
                html += '<td>' + item.Stock+ '</td>';
                html += '<td>' + item.Price + '</td>'; //Must show Currency sign in the beguining like $5,664.00
                html += '<td>' + item.Source + '</td>';
                html += '<td>' + item.COST + '</td>';
                html += '<td>' + item.Margin + '</td>'; // Must show % at the end of value
                //html += '<td><a href="#" onclick="return getbyID(' + item.Stock+ ')">Edit</a></td>';// | <a href="#" onclick="Delele(' + item.EmployeeID + ')">Delete</a></td>';
                html += '<td>' +sdg + '</td>'
                html += '</tr>';
            });
            $('.tbodyM').html(html);
        },
        error: function (errormessage) {
            alert(errormessage.responseText);
        }
    });
}

目前该表显示如下:

在此处输入图像描述

标签: javascriptajax

解决方案


Intl.NumberFormat是您的朋友。使用区域设置和货币创建一个新的格式化程序(我假设您在这里需要美元),它将生成格式化的字符串。

let formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
let price = formatter.format(item.Price);

鉴于您的示例数据,看起来可以使用字符串连接将百分比添加到末尾。


推荐阅读