Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core currency format did not work properly

While trying to display currency with the attribute [DataType(DataType.Currency)] and using @Html.DisplayFor(model => model.Variable), the format is not displaying correctly on my OS X computer while debugging locally. It shows up as a ¤ symbol instead of $.

like image 237
Bill Avatar asked Jan 04 '23 11:01

Bill


2 Answers

You can set the culture info programatically for your server in Startup.cs

public Startup(IHostingEnvironment env)
{
    CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");

    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}
like image 81
Aaron Roberts Avatar answered Jan 07 '23 12:01

Aaron Roberts


Here is another approach:

Model:

namespace WebApplication1.Models
{
    public class Employee
    {
        public decimal Salary { get; set; }
        public string SalaryUS
        {
            get { return string.Format(new System.Globalization.CultureInfo("en-US"), "{0:C}", Salary); }
        }
        public string SalaryPL
        {
            get { return string.Format(new System.Globalization.CultureInfo("pl-PL"), "{0:C}", Salary); }
        }
    }
}

Controller:

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            var model = new Employee()
            {
                Salary = 1000
            };

            return View(model);
        }
    }
}

View:

@model WebApplication1.Models.Employee

@Html.DisplayFor(model => model.SalaryUS) <br/>
@Html.DisplayFor(model => model.SalaryPL)

Result:

$1,000.00 
1 000,00 zł
like image 38
Michał Szymański Avatar answered Jan 07 '23 12:01

Michał Szymański