Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REGEX to format decimals using superscript in MVC4 Razor / Javascript

I am trying to format currency decimals using superscript, e.g. $1.08 instead of $1.08. Currently, my model currency variable (assume 1.08 value) shows as $1.08 using a model template and MVC4 Razor / Javascript:

[Range(0, 10000)]
[DataType(DataType.Currency)]
[DisplayFormat(DataFormatString = "{0:C}")]
public decimal Price { get; set; }

@{
    @Html.Display(model => model.Price)
}

Instead, I tried to extract and format decimals using REGEX, but it still displays as $1.08 (P.S. currency localization not important at this time):

@{
    var numRaw = Model.Price;
    var numSty = numRaw.ToString.Replace("(?<=\\.)([^.]*$)", "<sup>$1</sup>");
    @Html.Raw(numSty);
}

Note the double backslash \\. escape. The search expression seems to work correctly.

Am I doing something wrong in the "<sup>$1</sup>" replace string?

like image 831
Alfred Wallace Avatar asked Apr 29 '26 03:04

Alfred Wallace


1 Answers

Per @AndrewB and @SimonMcKenzie, Regex.Replace() must be used for Razor to work. The following code displays $1.08 as expected:

@using System.Text.RegularExpressions

@Html.Raw("$"+Regex.Replace(Math.Round(Model.Price,2).ToString(), "(?<=\\.)([^.]*$)", "<sup>$1</sup>"));
like image 147
Alfred Wallace Avatar answered Apr 30 '26 16:04

Alfred Wallace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!