如何在AJAX中对货币或百分比进行格式化?

时间:2022-09-15 08:52:39

What is the best way of formating the values to percentage or currency from Ajax and display to a Table?

将值或货币从Ajax中格式化并显示到表的最佳方式是什么?

I'm currently developing an application which has Money values from SQL Server and need to be format from 3569.09 to $ 3, 569.09 and also from 24.55 to 24.55 % on the Table.

我目前正在开发一个应用程序,它具有SQL Server的货币值,需要将格式从3569.09调整为$ 35569.09,并且还需要从24.55调整为24.55%。

I have the tried THIS but still did not help.

我试过了,但还是没用。

Here is JS my Code:

以下是我的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);
        }
    });
}

Currently the table shows like:

目前该表显示如下:

如何在AJAX中对货币或百分比进行格式化?

1 个解决方案

#1


3  

Intl.NumberFormat is your friend. Create a new formatter with a locale and currency (I’ll assume you want US dollars here) and it’ll produce formatted strings.

Intl。NumberFormat是你的朋友。使用语言环境和货币创建一个新的格式化程序(我假设您需要美元),它将生成格式化字符串。

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

Given your sample data it looks like the percentage can just be added on to the end using string concatenation.

对于示例数据,似乎可以使用字符串连接将百分比添加到末尾。

#1


3  

Intl.NumberFormat is your friend. Create a new formatter with a locale and currency (I’ll assume you want US dollars here) and it’ll produce formatted strings.

Intl。NumberFormat是你的朋友。使用语言环境和货币创建一个新的格式化程序(我假设您需要美元),它将生成格式化字符串。

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

Given your sample data it looks like the percentage can just be added on to the end using string concatenation.

对于示例数据,似乎可以使用字符串连接将百分比添加到末尾。