[英]Razor - how to get n number characters of string?
I have an asp.net mvc 4 application with the following 我有一个asp.net mvc 4应用程序,具有以下内容
Model 模型
public string Price {get;set;}
it saves in database a string, eg. 它在数据库中保存一个字符串,例如。 "41.99". “ 41.99”。
View 视图
@foreach(var item in Model)
{
<div class="price">@item.Price</div>
}
it returns the value "41.99" all good here. 它返回的值“ 41.99”都很好。
however I would like to pick the values differently. 但是我想选择不同的值。
Below is the Html output for what I need 以下是我需要的HTML输出
@foreach(var item in Model)
{
<div class="price">
<span class="dollar">41</span>
<span class="cents">99</span>
</div>
}
So how could I archive this? 那我怎么存档呢?
@foreach(var item in Model)
{
<div class="price">
<span class="dollar">@item.Price(first part)</span>
<span class="cents">@item.Price(second part)</span>
</div>
}
Any help or guindance would be apprecciated. 任何帮助或指导将不胜感激。
If your data is string then 如果您的数据是字符串,那么
var price = "41.99";
var parts = price.Split('.');
var dollar = parts[0];
var cents = parts[1];
If your data is decimal 如果您的数据是十进制
decimal price = 41.99m;
var dollar = (int)price;
var cents = (int)((price % 1) * 100);
Setting aside the fact you should not be using string to represent numerical values and use decimal
instead for money values... and the fact that .
撇开事实,您不应该使用字符串来表示数值,而应使用decimal
代替货币值...以及事实.
is not the only separator (depending on locale)... 不是唯一的分隔符(取决于语言环境)...
String.Split
is the easiest way to split the string on a separator: String.Split
是在分隔符上分割字符串的最简单方法:
var parts = item.Price.Split(`.`);
Now you have parts[0]
with "dollar" value, and need to deal with fractional part which may or may not be there. 现在,您具有具有“美元”值的parts[0]
,并且需要处理可能存在或可能不存在的小数部分。 Note that you may need to pad cents
value if you need something like 04
instead of just 4
请注意,如果您需要诸如04
而不是4
类的值,则可能需要填充cents
值
@{
var parts = @item.Price.Split('.');
var cents = (parts.Length == 2) ? cents = parts[1] : "0";
}
<span class="dollar">@parts[0]</span>
<span class="cents">@cents</span>
Thanks for all replies 感谢所有回覆
I figured it out combining the answers here with some suggestions. 我想出了结合这里的答案和一些建议。
here is the answer for my question: Model: 这是我的问题的答案:型号:
public double Price { get; set; }
Controller: 控制器:
public ActionResult Details(int id)
{
var data = _Context.Products.Where(d => d.ProductId == id).First();
if (data == null)
{
return HttpNotFound();
}
return View(data);
}
In View: 在视图中:
string s = Model.Price.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture);
string[] parts = s.Split('.');
int i1 = int.Parse(parts[0]);
int i2 = int.Parse(parts[1]);
<span>@i1</span>
<span class="decimal">@i2</span>
Works like a charm 奇迹般有效
Thanks a lot 非常感谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.