Format decimal to currency in @ViewBag

asp.net-mvc-3, razor

Solution

You can explicitly cast it to `decimal`; then you'll be able to treat it as though it were statically-typed.

@(((decimal)ViewBag.CalculatePrice).ToString("C2"))

If you were wondering how to specify formatting for a decimal, here's a reference for .NET's standard numeric formatting strings.

Problem

I am calling a decimal thusly in my view: ``` @ViewBag.CalculatePrice ``` How can I format that to represent $xxx.xx? CalculatePrice is just a `public decimal CalculatePrice() { //performing calculation }` in a class. Thanks.

Original source