1

I'm working with ASP MVC 5 and DataTables plugin and I'm having some problems formating my decimals.

I need to format numbers with dot as thousand separator and comma as decimal separator.

I'm trying to do it with DisplayFormat, but since i'm returning the data as Json, it just not applying

This is a little example of my problem

public class MyClass
{
   [DisplayFormat(DataFormatString = "{0:0.##}")]
   decimal MyDecimal {get;set;}
}

In the controller

public JsonResult LoadDataTables()
{    
    using(var db = new ExampleContext())
    {
        var data = db.MyRepository.Select(x => new MyClass
        {
            MyDecimal = x.mydecimal
        }).ToList();
        //i'm ignoring a lot of processing to create a short snippet
        return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data });
    }
}

Then, in the front end, the json arrives with comma for thousands and dot for decimal separation

How can i deal with it? Some way to apply CultureInfo or manually set the conversion?

Edit: In my view, this is how i'm loading the data

var table = $('#myTabla').DataTable({
                    processing: true,
                    serverSide: true,
                    filter: true,
                    orderMulti: false,
                    paging: true,
                    pageLength: 10,
                    ajax: {
                        "url": '@Url.Action("LoadDataTables")',
                        "type": "POST",
                        "datatype": "json",
                    });

Thanks!

Juan Salvador Portugal
  • 1,233
  • 4
  • 20
  • 38

3 Answers3

1

You need to set custom culture:

System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)
System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
customCulture.NumberFormat.NumberDecimalSeparator = ",";

System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;

Thank you.

Vishal Parmar
  • 524
  • 7
  • 27
Sonal Borkar
  • 531
  • 1
  • 6
  • 12
1

1 - You can do it in another way like this :

public class MyClass
{
   MyNumber MyDecimal {get;set;}
}

struct MyNumber
{
    decimal Value {get;set;}

    ToString()
    {
        // Adapt number Format and CultureInfo as wanted
        return value.ToString("0:0.##", MyCultureInfo);
    }
}

uses :

decimal d = MyNumber.Value

string s = (string)MyNumber; or MyNumber.ToString();

2 - Or on client side :

// Invert . and ,
// 1.22222.5689,56
// to 1,22222,5689.56
String.prototype.formatNumber = function(number)
{
    return number.replace(',', ';').replace('.', ',').replace(';', '.');
}

3 - My best choice to manipulate JSon in C# is : https://www.newtonsoft.com/json

You can serialize and deserialize json and creating custom conversion.

Shim-Sao
  • 2,026
  • 2
  • 18
  • 23
1

You can use Number helper for this. You can visit this link to refer more: https://datatables.net/manual/data/renderers#Number-helper

Here is a sample. Hope to help, my friend :))

//Code in Controller

public class Test
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Currency  { get; set; }
    }

private List<Test> Data()
        {
            var data = new List<Test>
            {
                new Test{ Id = 1, Name = "A1", Currency = 1000000.00M},
                new Test{ Id = 2, Name = "A2", Currency= 50000000.12M},
                new Test{ Id = 3, Name = "A3", Currency = 3000000.45M},
                new Test{ Id = 4, Name = "A4", Currency = 20000}
            };
            return data;
        }

        [HttpPost]
        public JsonResult LoadDataTables()
        {
            var data = Data();
            var recordsTotal = Data().Count;
            var recordsFiltered = Data().Count();
            string draw = Request.Form.GetValues("draw")[0];
            return Json(new { draw = Convert.ToInt32(draw), recordsTotal = recordsTotal, recordsFiltered = recordsFiltered, data = data }, JsonRequestBehavior.AllowGet);
        }

//View

<table id="myTable" >
    <thead>
        <tr>
            <td >Id</td>
            <td >Name</td>
            <td>Currency</td>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

    var table = $('#myTable').DataTable({
                    processing: true,
                    serverSide: true,
                    filter: true,
                    orderMulti: false,
                    paging: true,
                    pageLength: 10,
                    ajax: {
                            "url": '@Url.Action("LoadDataTables", "Home")',
                            "type": "POST",
                            "datatype": "json",
                    },
                    "columns": [
                        {
                            "data": "Id"
                        }, {
                            "data": "Name"
                        }, {
                            "data": "Currency",
                            render: $.fn.dataTable.render.number('.', ',', 2, '')
                        }
                    ]
                });
Tomato32
  • 2,145
  • 1
  • 10
  • 10