让产品价格小数点样式可控制
现在有不少店家喜欢购买自定义模板了,各种设计稿都有。有的设计稿还想让价格的小数点跟其他数字不一样,这个不加tag用纯css还真做不到。没办法只好把价格都格式化为有标签的html代码。
如图所示。
1 string GetPriceHtml(string price)
2 {
3 if (string.IsNullOrEmpty(price))
4 {
5 return string.Empty;
6 }
7
8 var numberFormat = Thread.CurrentThread.CurrentUICulture.NumberFormat;
9 var decimalSeparator = numberFormat.CurrencyDecimalSeparator;
10 var groupSeparator = numberFormat.CurrencyGroupSeparator;
11
12 if (price.Contains(decimalSeparator))
13 {
14 var numberRegex = new Regex(string.Format(@"[\{0}\d]+\{1}", groupSeparator, decimalSeparator));
15 price = numberRegex.Replace(price, delegate(Match match)
16 {
17 return string.Format(@"<span class=""number"">{0}</span>{1}", match.Value.Substring(0, match.Value.Length - 1), decimalSeparator);
18 });
19
20 var decimalRegex = new Regex(string.Format(@"\{0}\d+$", decimalSeparator));
21 price = decimalRegex.Replace(price, delegate(Match match)
22 {
23 return string.Format(@"<span class=""decimal-separator"">{0}</span><span class=""decimal"">{1}</span>", decimalSeparator, match.Value.Substring(1));
24 });
25 }else
26 {
27 var numberRegex = new Regex(string.Format(@"[\{0}\d]+", groupSeparator));
28 price = numberRegex.Replace(price, delegate(Match match)
29 {
30 return string.Format(@"<span class=""number"">{0}</span>", match.Value);
31 });
32 }
33
34 var symbol = numberFormat.CurrencySymbol;
35 price = price.Replace(symbol, string.Format(@"<span class=""symbol"">{0}</span>", symbol));
36
37 return price;
38 }
测试代码:
1 void Main()
2 {
3 Thread.CurrentThread.CurrentUICulture = new CultureInfo("nl-NL");
4 Console.WriteLine(GetPriceHtml("€ 2.300,20"));
5 }
结果:
<span class="symbol">€</span> <span class="number">2.300</span><span class="decimal-separator">,</span><span class="decimal">20</span>