Formating decimal JsonResult ASP MVC 5

newtonsoft json serialize decimal places
json decimal precision
decimal model binder mvc
asp net core custom json converter
json net typeconverter
c# serialize decimal
jsonproperty c#
web api json serializer settings

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!

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, '')
                        }
                    ]
                });

JSON and .NET Decimals, JavaScript sees that the Speed is just “5” (it's weakly typed, so it interprets that as an integer). When .NET tries to cast that as a decimal it chokes  JsonResult is one of the type of MVC action result type which returns the data back to the view or the browser in the form of JSON (JavaScript Object notation format). In this article we will learn about JsonResult by taking scenario to bind view using the JSON Data .

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.

Decimal binding problem on non English Culture · Issue #5331 , How can I accept numbers in json format in my culture that does not accept MVC core does not treat JSON and form-data as the same. ASP.NET MVC JsonResult Date Format . Posted by: admin December 9, 2017 Leave a comment. I am using asp.net 3.5, vs 2008, asp.net MVC 2, and jquery week calendar,

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.

Sending decimal as JSON, Hello, i have a problem when sending decimal values with json. Can you sugest some proper way so when the user writes number in 0.00 or 0,00 format i'​ll be able to get the proper value no matter NET Videos 5 minutes. That registers our model binder to only be applied to decimal types, which is good since we wouldn’t want model binding to try and use this model binder when binding any other type. With this in place, the Salary field will now accept both 1234567.55 and 1,234,567.55 .

convert json data value to decimal, convert json data value to decimal [Answered]RSS. 5 replies. Last post Jan 08, 2014 12:25 PM by Nilu87 · ‹ Previous Thread|Next Thread ›. Print Share. This article will provide you an idea of JsonResult, JsonResult Properties, the use of JsonResult with various scenarios and how can you test the JsonResult by using Test Project in a MVC application.

JSON and XML Serialization in ASP.NET Web API, Describes the JSON and XML formatters in ASP.NET JSON and XML Serialization in ASP.NET Web API. 05/30/2012; 9 minutes to read. +5 In ASP.​NET Web API, a media-type formatter is an object that can: public class Product { public string Name { get; set; } public decimal Price { get; set; } [JsonIgnore] public int  The default format used by ASP.NET Core MVC is JSON. Content negotiation is implemented by ObjectResult . It is also built into the status code specific action results returned from the helper methods (which are all based on ObjectResult ).

Model Binding Decimal Values, I'll talk to the rest of my team about whether we should fix this in the next version of ASP.NET MVC, but for now it's good to know there's a  Hi zjm_zjm, zjm_zjm. and I want when to load decimal value to price textbox format is. 10.000.000,23. default is 10000000,23. For this problem I think you could add DisplayFormat when you create a model.

Comments
  • Could you show your code in View, my friend?
  • Here is the documentation for ToString() output format : docs.microsoft.com/en-us/dotnet/standard/base-types/… . You can apply CultureInfo for output.
  • @Tomato32 Addeded how i load the data, my view is only one table and that script basically
  • @Shim-Sao the problem is where must i apply that? the DisplayFormat annotation never happen
  • @JuanSalvadorPortugal your JSON is just fine. Using dots is the defacto standard for numbers in JSON. It's you DataTable configuration that should specify how that decimal field gets displayed
  • Hi, thanks for answer! i try it, but the result is the same :(
  • Have you removed the attribute [DisplayFormat(DataFormatString = "{0:0.##}")]?
  • Yes i'm, i already had the culture configured, my problem is, for some reason its not get applyed to the Json conversion
  • Read this post stackoverflow.com/questions/35709595/…