1

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

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.

I have the tried THIS but still did not help.

Here is JS my Code:

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:

enter image description here

Kiran Joshi
  • 1,758
  • 2
  • 11
  • 34
PatsonLeaner
  • 1,230
  • 15
  • 26

1 Answers1

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.

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.

Robin Whittleton
  • 6,159
  • 4
  • 40
  • 67